S.O.L.I.D. : 2. Open Closed Principle

This princple says-

Classes should be open for extension, but closed for modification.


If we have actions that depend on the subtype of a class, it is easier to provide that feature in the parent class, and then the subclasses can reimplement that feature by polymorphism (OOP).

The problem here is that the classes should be open to extension and closed to change. Let’s see it clearer with the example.


In this example, we have 2 shapes classes “Circle” and “Square” and an another class “AreaCaculator” class to calculate the area of these types of shapes.

This example will work fine in case all the shapes are either type of Circle or Square, because we have  hardcoded checks in sum() function of AreaCaculator class for Circle and Square.

Now if we need to add an another shape like Rectangle or Triangle, then we have to modify AreaCaculator class to make it able to calculate the area of Rectangle or Triangle. And is the violation of this principle. Class should be able to extent without any modification.

So if we follow this rule then the structures of class should be like –


Next Principle >>

<< Previous Principle

Please follow and like us: