SOLID Principles With .NET - Open Closed Principle
The Open Closed Principle
is the SOLID principle which states that the software entities (classes or methods) should be open for extension but closed for modification.
Open for extension but closed for modification ? Oh what does it really mean ?
In real time every business requirements changes so frequently, so while developing an application we should strive to write a code that doesn't require modification every time business changes it requirement.
The biggest benefit for an application to be adhered to OCP is, it potentially streamlines code maintenance and reduces the risk of breaking the existing implementation.
Here , I will show you how we can implement a requirement with and without OCP rules.
This article is divided into the following sections :
Banking Service Calculator
Based on the type of account the bank decided to pay annual interest , and for that my model with OCP looks something like this ,
Now the business asked to add another account type ( corporate account with 6 percent interest). So , now I need to again change the same model as below :
Even though the business requirement is achieved , but it is completely violating the Solid principles .
Now we are going to implement the same using OCP .
We can apply OCP by using interface , abstract class , abstract methods , virtual methods when you want to extend functionality. Here I have used an abstract class as example and used it as base class
In the above code three new classes are created ; SavingsAccount,SalaryAccount,CorporateAccount by extending them from Account.
This solves the problem of modification of class and by extending interface , we can extend functionality.
Now if we need to add a new requirement to add Money Market account , it can be easily implemented without modifying but by just extending .
By using the InterestCalculator class it is much more simpler and robust as it can handle any type of shape now .
In this article we have covered how the OCP is implemented and in the next article we can see how the Liskov Substitution Principle (LSP).
The code for the above example is accessible on Git Hub.
Comments
Post a Comment