Open/Closed Principle
The Open-Closed Principle (OCP) is a principle of object-oriented programming that states that software entities (such as classes, modules, and functions) should be open for extension but closed for modification.
This means that you should be able to add new functionality to a software entity by extending it, without changing the existing code. This can help to ensure that the entity is flexible and maintainable, as changes to the entity can be made through extension rather than modification.
Here is an example of a class that does not follow the Open-Closed Principle:
In this example, the Shape
class has a single method, area
, which calculates the area of a shape based on its type. However, this design violates the Open-Closed Principle, because we would need to modify the area
method every time we want to add a new type of shape or change the way the area is calculated.
Here is how we could refactor this code to follow the Open-Closed Principle:
In this revised design, the base Shape
class defines the core functionality (such as having an area
method), and the derived Circle
and Rectangle
classes add additional functionality (specific formulas for calculating the area) through inheritance. This design follows the Open-Closed Principle, because we can extend the functionality of the Shape
class by creating new derived classes, without modifying the existing code.