Open Closed Principle: Definition, Example, and Usage
Open Closed Principle means software entities like classes or functions should be open for extension but closed for modification. This means you can add new features without changing existing code, making systems easier to maintain and less error-prone.How It Works
Imagine you have a toy robot that can do many things. Instead of opening the robot and changing its parts every time you want it to do something new, you add new attachments that connect to it. The robot itself stays the same, but it can do more because of the new parts.
In software, the Open Closed Principle works the same way. You design your code so that you can add new features by adding new code, not by changing the old code. This helps keep the old code safe and stable, reducing bugs.
It encourages using things like interfaces or abstract classes where new behaviors can be added by creating new classes that follow the same rules, without touching the existing ones.
Example
This example shows a simple way to calculate areas of shapes. Instead of changing the calculator when adding new shapes, we add new shape classes.
from abc import ABC, abstractmethod class Shape(ABC): @abstractmethod def area(self) -> float: pass class Rectangle(Shape): def __init__(self, width: float, height: float): self.width = width self.height = height def area(self) -> float: return self.width * self.height class Circle(Shape): def __init__(self, radius: float): self.radius = radius def area(self) -> float: return 3.14159 * self.radius * self.radius class AreaCalculator: def total_area(self, shapes: list[Shape]) -> float: return sum(shape.area() for shape in shapes) shapes = [Rectangle(3, 4), Circle(5)] calculator = AreaCalculator() print(f"Total area: {calculator.total_area(shapes)}")
When to Use
Use the Open Closed Principle when you expect your software to grow with new features over time. It is especially useful in large projects where changing existing code can cause bugs or break other parts.
For example, in a payment system, you might start with credit card payments. Later, you add PayPal or other methods by adding new classes without changing the old payment code.
This principle helps teams work safely on different parts of the system without interfering with each other.
Key Points
- Software entities should be open for extension but closed for modification.
- Use interfaces or abstract classes to allow new behaviors.
- Helps keep existing code stable and reduces bugs.
- Makes adding new features easier and safer.