In the first part, we described that what is the SOLID principles and the first rule of the SOLID principle which is “Single Responsibility principle” and what they try to solve, if you did not read that article then I recommend you to read that article first from the link given here.
In this article, we are going to explain the next principle in the series of SOLID principles which is the Open Close Principle.
Open Close Principle
The open-closed principle was defined by Bertrand Meyer in 1988.
open-closed principle states that “Software Entities (classes, modules, functions, etc) should be open for extension, but closed for modification”.
As a Developer, sometimes we have new requirements adding new features to the existing entities or having to change the business logic. so we have to keep the application in such a way that it may remain intact. we have to take care that no other module or class would not be affected while we’re adding or changing code.
so every time, when we are trying to change or modify the existing module, the open-close principle comes into the picture.
you can understand this principle by a very simple example that is given below. you can also download the code sample from the given link here.
here is given an example so that you can understand the concept better.


In the above code example, you see a class name Rectangle which is used for calculating the area of the rectangle using height and width. class MeasueArea uses class Rectangle as a construction injection and call calculate functionn. to calculate the area of rectangle.



every time you extend the functionality for the new shape you have to make a separate class for that shape and a function for calling that function in Measure Area class.
one way to handle this problem is to use protocol. Here, you can download the code sample



if you further want to add functionality for a new shape you have only created a class for that shape and nothing else this reduces the coupling between the modules and increases the performance and make the code easy to maintain. Download Code From Here


Conclusion
Open-closed principle makes our code easier to maintain and extend. Sometimes, when we write code, we don’t see the need to create abstractions, but then we’ll probably need it.
I hope you like this piece and that it was helpful to you. Thanks for reading.