The Open/Closed Principle states that a module (such as a class, function, etc.) should be open for extension but closed for modification. In other words, a module should be designed in such a way that it can be easily extended without changing its existing code.
Here's an example in Python:
In this example, the Shape
class is an abstract base class that defines the interface for all shapes, and the Circle
and Rectangle
classes inherit from it and provide concrete implementations of the area method. The calculate_area
function takes a list of shapes and calculates the total area by calling the area method on each shape.
By using inheritance and an abstract base class, the existing code can be extended to support new shapes without having to modify the existing code. For example, if we wanted to add a square shape, we could simply create a Square
class that inherits from Shape
and provide an implementation of the area method. This adheres to the Open/Closed Principle as the existing code remains closed for modification, while new functionality can be added through extension.
Python
Design Patterns
Clean Code Studio
Python Design Patterns
Python Open Closed Principle Design Pattern
Open Closed Principle (OCP)
Top comments (0)