Open Closed Principle
We will be discussing the Open-Closed Principle also known as OCP, as one of the SOLID principles of object-oriented programming and how to implement it when designing our software.
This principle said that should be open for extension but closed for modification. We should write a code that does not require modification every time a customer changes its request.
Example
Let us define a class that contains salary calculations.
Let us imagine that we have a task where we need to calculate the total cost of all the developer salaries in a single company.
To get started, we are going to create the model class first,
We can design the salary calculation method in another class.
Then call this method on the main program.
So, all this solution is working great, but now our team leader comes to our desk and says that we need a different calculation for the senior and junior developers. The senior developers should have a bonus of 20% on a salary.
Of course, to satisfy this requirement, we are going to modify our CalculateTotalSalaries method like this,
Mainly, because we had to modify our existing class behavior which worked perfectly. Another thing is that if our team leader comes again and asks us to modify the calculation for the junior devs as well, we would have to change our class again. This is totally against what OCP stands for.
Again, Modify the code as per OCP Principle,
Define another class for SeniorDevSalaryCalculator.cs,
Conclusion
Even though the name of the principle is self-explanatory, we can see how easy it is to implement incorrectly. Make sure to distinguish the logic of every class -- it does not need to change the current class if you have more categories, but you must extend the abstract class and perform the logic and implementation as per requirement comes.
Comments
Post a Comment