OCP (Open/Closed Principle) — Explained with Examples
The Open/Closed Principle states that classes should be open for extension but closed for modification, enabling new behavior without altering existing code.
OCP stands for Open/Closed Principle, the second of the five SOLID principles. Bertrand Meyer introduced it in 1988: “Software entities should be open for extension, but closed for modification.”
Why OCP Matters
Every time you modify existing, working code to add a feature, you risk introducing bugs. OCP solves this by designing systems where new functionality is added through new code (extension), not changes to proven code (modification). This reduces regression risk and keeps the codebase stable.
Real-World Analogy
A power outlet is open for extension (you can plug in any device) but closed for modification (you don’t rewire the outlet for each new device). The outlet defines a stable interface, and devices implement that interface to add their specific behavior.
Example: Violating vs Following OCP
# Violating OCP — adding a new shape requires modifying the AreaCalculator
class AreaCalculator:
def calculate(self, shape):
if shape.type == "circle":
return 3.14 * shape.radius ** 2
elif shape.type == "square":
return shape.side ** 2
# Adding triangle requires a new elif branch
# Following OCP — new shapes don't change existing code
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * self.radius ** 2
class Square(Shape):
def __init__(self, side):
self.side = side
def area(self):
return self.side ** 2
class Triangle(Shape):
def __init__(self, base, height):
self.base = base
self.height = height
def area(self):
return 0.5 * self.base * self.height
# AreaCalculator now works with any Shape without modification
calculator = AreaCalculator()
shapes = [Circle(5), Square(4), Triangle(3, 6)]
for shape in shapes:
print(calculator.calculate(shape))Related Terms
SOLID, Single Responsibility Principle, Liskov Substitution Principle, Polymorphism
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro