it states that the software entities (classes, modules, functions,..etc.) should be open for extension but closed for modification.
in this principle we want to be able to add a new behavior ‘open to extension’. without the need to change our source or binary code ‘closed to modification’. or in other words we should strive to write code that doesn’t have to be changed every time the requirements change.
huh! change behavior without changing the code. !!
Yes we can achieve this by relying on abstraction (Interfaces, Abstract Base Classes) because there is no limit to number of different ways we can implement that abstraction .
An Example :
Suppose that there is a class called Rectangle that has a width and height properties within it.
and a class called AreaCalculator that calculates the area of the rectangle by multiplying its width and Height.
Now every thing works fine but what if we want to add another feature to AreaCalculator class that makes it able to
calculate the area of circle too.
hmmm… there will be no problem with that .
first I’ll make a circle class
then I will update my AreaCalculator class to be like this :
once again what if we want to extend our AreaCalculator class to also calculate the area of a triangle too.
Of course in this very basic example it is not hard for us to implement it but it does require us to modify the code again and this is not good .Imagine In a real world example where the code is ten, a hundred or a thousand times larger, modifying the class everytime a new requirement is needed can be a pretty big problem .
So we want to close our AreaCalculator for modification and make it open for extension.
I’ll create a base class called shape for both rectangles, circles and any other shapes that will be added in the future. the shape class defines an abstract method for calculating it’s area.
and both the Rectangle and the Circle classes will inherit from the Shape class:
As the Area method in the base class ‘Shape’ is abstract then the two area methods inside the Circle and Rectangle classes will override it and each one will provide its own implementation of the method.
Now the Area method of the AreaCalculator class is not responsible for the actual calculating of the area it can deal with any type of shapes we throw at it and the code is much simpler.