SOLID: Open Closed Principle

Learn about the Open Closed Principle and its implementation in real-world problems.

Introduction

In 1988, Bertrand Meyer defined the Open Closed Principle (OCP) in the following way, “A software artifact should be open for extension but closed for modification.” This means that a system should improve easily by adding new code instead of changing the code core. This way, the core code always retains its unique identity, making it reusable.

One might think of OCP as inheritance, but remember that inheritance is only one of the OCP techniques. We use the interface because it is open for extension and closed for modification. Therefore, OCP is also defined as polymorphic OCP.

Example

Suppose Alex had a cardboard business that sold boxes to its clients. We designed a class for calculating the volume of boxes. It takes the dimensions and calculates the volume of each box and adds it up to calculate the total volume of all boxes, as shown below.

Level up your interview prep. Join Educative to access 70+ hands-on prep courses.