Open-Closed Principle – Interview Question with awesome Answer

(Last Updated On: November 6, 2016)

Interview Question: Explain Open – closed Object Oriented Design Principle with program and example. What is benefit of using Open closed principle?

NOTE: To answer this question, we should be explaining what the problem is without using Open Closed principle and what we get using Open- Closed principle with a program example.

Answer: Open – Closed Object Oriented design principle states that “A class, module should be open for extension and Closed for modification”.

Once we have written a class it should not be modified again and again over time, but yes, it should be open for extension. If we modify a class over and over it will require testing efforts and time over and over as there could be chance for functional issue, logical issues and if we have a class in binary form it need be recompiled etc.

 

Let’s understand Open closed principle with example.

Consider an example, we have a “Canvas” class that will access multiple shape classes i.e. Circle and Square etc. to draw shapes over Canvas.

Example – without applying Open closed principle

Below, we have two Concrete shape classes “Circle” and “Square” and one “Canvas” class. Canvas class is composed of Circle and Square class i.e. have objects of these classes and in drawSapes() method it will call draw() methods of shape classes using Circle and Square objects.

 

 

Now, Let’s Say, some later point of time we get another type of shape to implement. For example, “Rectangle”.

Then Canvas class requires modification as we have to compose Rectangle object in this class. Means, the Canvas class is not closed for modification. This is violation of Open-Closed principle.

 

Example – applying Open closed principle

Implement the same using Shape interface and use interface in Canvas class to access different shape objects.

 

 

In this design, if we get a requirement for new shape implementation, we don’t have to modify Canvas Class. Just we need to extend the Shape with Rectangle class like below.

 

In this design, we have just extended Rectangle shapes and no class requires modification. You extend shapes or remove shapes, Canvas class is not required to modify. This design follow the Object Oriented Open-closed design principle.