Open/Closed Principle – SOLID Principles
Satya Prakash Chhikara
.NET 8 | .NET Core | ASP.NET | MVC | Software Development | Mobile Development | Web Development | ERP | CMS | Microsoft Technologies | AI Automation | DevOps | AWS | Azure
Open/Closed Principle – SOLID Principles
A software module/class is open for extension and closed for modification.
Open for extension means that we must build any class/module so that new functionality can be added when there is new requirement in software.
Closed for modification means that we have already built a class, and we are done with unit testing, so we won’t change this class until and unless a bug has not been reported.
Confused??? Okay, let me explain with an example.
Suppose we are designing software for a bank. Initially the bank is starting business with Loan Account only.
Based on requirements, developer made 2 classes (One for LoanAccount and another to calculate interest)
?
And
?
Initially everything looked good and was working.
Let’s say, after 1-2 years, bank started working on retail as well and added one more account type (Saving Account)
To meet requirements, developers made changes and add one more account class.
?
And updating existing class like
By doing so, the developer was able to add one more account type successfully. Let’s say we need to add more account “Current Account”, so in same way, we can add one more class for Current account and update function Calculate Interest
But every time, when we add new account type, we need to modify “InterestCalculator” class function “CalculateInterest” which violates “Open close” principle.
To satisfy close principle, we shouldn’t modify “InterestCalculator” if we need to add more account type.
We can re-design this to meet “open for extension and close for modification” like below
We first made an interface having method defined as CalculateInterest.
?
?
?
And finally, Interest Calculator class like
?
Now, we can add as many as account types into software without modify InterestCalculator class
?
?
?
?