In this article, we will see the open closed principle, one of the SOLID design principles, in detail.
Open-Closed Design Principle (OCP)
The Open-Closed Design Principle (OCP) is a software development principle that states that software entities should be open for extension but closed for modification.
That means, software should be designed in a way that allows new features to be added through extension, without modifying existing code.
This principle encourages the creation of code that is easier to maintain, test, and extend over time.
Open Closed Principle Example in C#
Let’s see an example of the Open Closed Principle in a .NET Core, let’s consider a simple banking application that handles different types of accounts, such as SavingsAccount and CurrentAccount.
We can use OCP to ensure that the application can easily handle new types of accounts without modifying existing code.
First, we define an abstract base class called Account that represents the common functionality of all account types:
public abstract class Account
{
public string AccountNumber { get; set; }
public decimal Balance { get; set; }
public abstract decimal CalculateInterest();
}
This class defines two properties that are common to all accounts, account number, and balance as well as an abstract method CalculateInterest(), which calculates the interest earned by the account.
Next, we define two classes that inherit from Account, SavingsAccount, and CurrentAccount and then implement the CalculateInterest() method in each:
public class SavingsAccount : Account
{
public override decimal CalculateInterest()
{
// calculate interest for savings account
}
}
public class CurrentAccount : Account
{
public override decimal CalculateInterest()
{
// calculate interest for checking account
}
}
Now, let’s say we want to add a new type of account, a MoneyMarketAccount.
We can do this without modifying the existing code by simply creating a new class that inherits from Account and implements the CalculateInterest() method:
public class MoneyMarketAccount : Account
{
public override decimal CalculateInterest()
{
// calculate interest for money market account
}
}
By following the Open-Closed Design Principle, we have created a codebase that is open for extension.We can add new types of accounts without modifying existing code.
At the same time, the remaining part is closed for modification, we do not need to modify the existing base class or any of its derived classes to add new functionality.
Summary
Open closed principle is very important in code maintainability and extensibility. Hope you found this article useful.
Leave a Reply