OCP
OCP — Open/Closed Principle
"Software entities should be open for extension, but closed for modification." — Bertrand Meyer, Object-Oriented Software Construction (1988)
"You should be able to add new behaviour without changing existing code." — Robert C. Martin, modern reformulation
Core idea
A class, module, or function should be designed so that new behaviour is added through new classes, without changing what is already written. This is achieved through polymorphism: a shared interface (Protocol or ABC) plus different implementations that plug in as components.
Why it matters
| Without OCP | With OCP |
|---|---|
| Every new requirement requires editing an existing class | A new requirement means a new class; the old ones are untouched |
| Changes are risky, you might break what works | The old works, the new is added safely |
| Existing test cases must be re-run | New tests only for the new class |
| Code reviews are large, lots of changes | Reviews are small, just the new class |
| Files grow with every feature | Files stay stable, new ones appear next to them |
| Paradox: a working system fears new features | The system can be extended indefinitely |
Classic anti-pattern: if/elif on the type
def calculate_area(shape: dict) -> float:
if shape["type"] == "circle":
return 3.14159 * shape["radius"] ** 2
elif shape["type"] == "rectangle":
return shape["width"] * shape["height"]
elif shape["type"] == "triangle":
return 0.5 * shape["base"] * shape["height"]
else:
raise ValueError(f"Unknown shape: {shape['type']}")
What is wrong here:
- Adding a "trapezoid" means editing
calculate_area. - Every edit risks breaking the working branches.
- Tests for
circlehave to be re-run aftertrapezoidis added. - If
shape["type"]comes from a config or API, adding a new type requires a synchronous change in two places. - The logic for each shape duplicates wherever else it is used (in
perimeter(), for example).
Standard solution: Strategy + Protocol
from typing import Protocol
class Shape(Protocol):
def area(self) -> float: ...
class Circle:
def __init__(self, radius: float): self.radius = radius
def area(self) -> float: return 3.14159 * self.radius ** 2
class Rectangle:
def __init__(self, w: float, h: float): self.w, self.h = w, h
def area(self) -> float: return self.w * self.h
class Triangle:
def __init__(self, base: float, height: float): self.base, self.height = base, height
def area(self) -> float: return 0.5 * self.base * self.height
def total_area(shapes: list[Shape]) -> float:
return sum(s.area() for s in shapes) # ← DOES NOT CHANGE
Now adding a "trapezoid":
class Trapezoid:
def __init__(self, a, b, h): self.a, self.b, self.h = a, b, h
def area(self) -> float: return 0.5 * (self.a + self.b) * self.h
That is it. No existing class is touched. total_area, Circle, Rectangle, Triangle are all untouched. "Closed for modification, open for extension."
OCP is a consequence of polymorphism plus composition
OCP usually appears for free when you do other things right:
- Adding
SmsNotifierwithout editingOrderProcessor. That is OCP. - Swapping
listfordequeinside a Stack without changing the API. OCP at the storage level. - Adding
PostgresUserRepositorywithout editingRegistrationService. OCP at the implementation level.
OCP is not a separate mechanism. It is a consequence of using Protocol + DI well. If you got SRP right, you probably got OCP for free.
Strategy Pattern — the formal name of the OCP pattern
The Strategy pattern (GoF) is OCP in OOP form:
┌─────────────────────────────────────┐
│ Context (PriceCalculator) │
│ ────────────── │
│ holds a reference to a strategy │
│ delegates the varying logic to it │
└────────────┬────────────────────────┘
│ uses
↓
┌─────────────────┐
│ Strategy │ ← Protocol/ABC
│ (DiscountRule) │
└─────────────────┘
↑
┌─────────┼─────────┐
│ │ │
┌──────┐ ┌──────┐ ┌─────────┐
│ Vip │ │ Gold │ │ Holiday │ ← concrete strategies
└──────┘ └──────┘ └─────────┘
Each strategy is a small class with one method. The context (the consumer) takes a strategy through its constructor and calls it, without knowing which one.
Composing strategies
OCP becomes really powerful when strategies can be combined:
class Discount(Protocol):
def apply(self, amount: float) -> float: ...
class NoDiscount:
def apply(self, amount): return amount
class PercentDiscount:
def __init__(self, rate: float): self.rate = rate
def apply(self, amount): return amount * (1 - self.rate)
class CompositeDiscount: # ← also a Discount!
def __init__(self, discounts: list[Discount]):
self._discounts = discounts
def apply(self, amount):
for d in self._discounts:
amount = d.apply(amount)
return amount
# Stacking discounts:
discount = CompositeDiscount([
PercentDiscount(0.10), # tier discount
PercentDiscount(0.05), # seasonal discount
])
The composite is itself a strategy. That makes the system infinitely extensible without touching existing code.
Should you always avoid if/elif?
No. OCP does not mean "no if". if is a basic language construct. The question is what you branch on:
| Branching on | OCP? | Why |
|---|---|---|
if/elif on type or category (if type == "circle") |
❌ Often a violation | Each new type means an edit |
if/elif on a value in a range (if age >= 18) |
✅ Normal | This is a rule, not polymorphism |
if/elif on a mode or state (if state == "open") |
⚠️ Depends | If states keep growing, this becomes State Pattern |
if on empty / non-empty |
✅ Normal | Basic logic |
if/elif with more than 3-4 branches that keep growing |
❌ Often a violation | Built-in exponential growth |
Rule: if the same
if/elif/elserepeats in several places for the same types, that is an OCP signal. Time for Strategy.
Anti-patterns
1. isinstance chains
def render(component):
if isinstance(component, Button):
...
elif isinstance(component, TextField):
...
elif isinstance(component, Checkbox):
...
Same as if type == "...", only with types. Fix: put render() on the component itself.
2. A big match/case on type
match shape:
case Circle(r): ...
case Rectangle(w, h): ...
case Triangle(b, h): ...
Python 3.10+ gives you match. It is useful for closed sets (AST nodes, for example, where the list is fixed). For open sets (shapes, customer tiers, formats), it is the same OCP violation.
3. "We will add it later" — empty strategies
class FutureDiscount:
def apply(self, amount): return amount # ← placeholder "for later"
That is a YAGNI violation. Wait until you need it.
4. OCP through inheritance
class BasePriceCalc:
def calculate(self, amount):
return amount * (1 - self.get_rate())
class SilverPriceCalc(BasePriceCalc):
def get_rate(self): return 0.05
class GoldPriceCalc(BasePriceCalc):
def get_rate(self): return 0.10
It works, but:
- Tight coupling to the base (Fragile Base Class).
- A separate class per variant — Java-style overhead.
- You lose composition.
Better: strategy through composition (Discount as a parameter, not a parent).
5. OCP for the sake of OCP
class GreetingStrategy(Protocol):
def greet(self) -> str: ...
class HelloGreeting:
def greet(self): return "Hello"
If you have one implementation and no plans for a second, OCP is not needed. That is YAGNI. A plain function def greet(): return "Hello" is enough.
How to tell OCP is about to be needed
- You see
if/elif/elseon three or more types. - You notice the same
if/elifduplicated in several functions. - The list of variants in a config or DB keeps growing.
- In reviews you hear "let's add one more
iffor Y". - A product request: "we need one more type".
If at least one of these matches, refactor to Strategy.
Don't confuse: OCP is NOT "never change any code EVER"
OCP is not magic. It is about:
- The preferred unit of extension (a new class).
- Extension points have to be DESIGNED (Protocol + DI).
- The Protocol itself and the composition root still change, and that is fine.
If a new customer type needs a new field in DiscountContext, that is a new Protocol signature, and that changes. OCP protects against small changes per type, not against architectural evolution.
Rule of thumb: adding the Nth variant in a category should require editing no more than 2 files (the new class + 1 line of registration / injection). More than that, OCP is broken.
Relationship to other principles
- SRP — OCP is impossible without SRP. If a class has 5 responsibilities, a new feature will inevitably touch one of them.
- DIP — the Protocols and ABCs you use for OCP are dependency inversion in action.
- Composition > inheritance — OCP through composition is more flexible than OCP through inheritance.
- Polymorphism — the mechanism through which OCP is implemented.
Rules of thumb
- Before adding another
elif, ask whether this is really Strategy. - An
isinstancechain is almost always an OCP violation. - Strategy Pattern (Decorator Facade for stacking, Composite Proxy for trees of strategies) is the standard way to combine interchangeable algorithms.
- Wait for two or three real variants before extracting a Protocol. Otherwise YAGNI.
- One Strategy class for one variation. Do not try to cover "all possible cases" with one class.
- The composition root knows all the strategies and wires them together. That is normal.
- OCP is a consequence of good design, not a goal. Do not "do OCP". Do SRP + Protocol + composition, and OCP shows up on its own.
One-line summary
Add new variants through new classes, not through new
elifbranches. Strategy + Protocol + DI is the standard recipe. If you got SRP right, you already have OCP.