Open/closed principle
medium 55 minCode should be open for extension and closed for modification: a new kind of thing arrives as new code, and the code that already works stays as it is.
Video lesson · Chapter 1 of 6
Make a prediction
Open/closed principle
1:03Reel
More reels
One idea each, a minute or less.
Spot it: open/closed
0:33Reel
Theory
Read or listen first. About 3 min.
What it is
The open/closed principle (OCP) says that a class, a module or a function should be open for extension and closed for modification. Open: you can make it do something new. Closed: you do that without editing its tested code.
The two halves sound like a contradiction. They fit together through a contract in the middle. The stable part calls the contract. Each new behaviour is a new piece of code that keeps the contract. The stable part never learns its name.
It is the O in SOLID. It is not a promise that code never changes. Bugs are fixed, and somebody must write one line that switches the new piece on. The promise is smaller and more useful: for one kind of change that you chose, the core stays as it is.
Why it exists
Every edit to working code can break what worked. If ten kinds of discount live in one method, a change for the eleventh puts all ten at risk, and all ten must be tested again. If each lives in its own class, the change adds one class and one test.
It also lets people work side by side. Two teams that edit the same method collide in every merge. Two teams that add a class each do not meet at all.
And it decides who may extend your program. When new behaviour needs an edit of your source, only you can add it. When it needs a class that keeps a contract, a colleague, a customer or a stranger can.
A short history
1988
Bertrand Meyer names the principle in Object-Oriented Software Construction. The Meyer version: a module is closed once others can use it, and it is extended by a descendant class through inheritance, so its users are not disturbed.
1996
Robert C. Martin publishes The Open-Closed Principle in the C++ Report (January). The Martin version moves the weight to abstract interfaces with many implementations. The article also says that no program can be closed against every change, so the choice must be strategic.
1996
Alistair Cockburn describes Protected Variations in Pattern Languages of Program Design 2, without knowing OCP: find where change is expected and build a stable interface around it.
1998
Philip Wadler names the expression problem: adding new types and adding new operations pull a design in opposite directions.
2001
Craig Larman writes in IEEE Software (May/June) that OCP and Protected Variations are essentially the same idea, relates both to information hiding by David Parnas, and warns about speculative future proofing.
2014
In a blog post Robert C. Martin calls plugin systems the ultimate form of the principle.
Words to know
- Extension
- New behaviour that arrives as new code.
- Modification
- An edit to code that already works and is already used.
- Extension point
- The place where new code can be attached: an interface, a hook, a list of rules.
- Contract
- What the core may expect from every extension, including limits such as never negative.
- Axis of change
- One kind of change, such as a new discount. A design is closed along some axes and open to edits along others.
- Composition root
- The one place that creates objects and connects them. Here a new extension is switched on.
- Registry
- A table from a name to a way of making the extension with that name.
- Meyer's OCP
- Extend by inheriting from a finished class.
- Polymorphic OCP
- Extend by writing another implementation of an interface.
- Protected Variations
- Find the expected variation and put a stable interface around it.
- YAGNI
- You aren't gonna need it: do not build for a change nobody has asked for.
The solution, twice
Reach the regular design first. Then go where a FAANG interviewer digs.
How it works
Step through the idea, or press Play.
Spot the axis. Which edit keeps coming back to the same method?
Understand it
Start here
Do not open the wall for every lamp
Noor buys a lamp, then a fan, then a radio. There are two ways to give each of them power. One opens the wall each time. The other opens it once, and never again.
Frames 1 to 3 are the if chain, 4 and 5 are the principle, 6 to 8 are the three things people forget: adapters, promises and moderation.
The smell
Code that asks: what kind are you?
A shop gives 10% to regular, 20% to premium and 30% to VIP customers. The first version is honest and short. Look at what happens as the shop grows.
def total(subtotal, tier, code, mugs, mug_price): discount = 0 if tier == "regular": discount += subtotal * 10 // 100 elif tier == "premium": discount += subtotal * 20 // 100 elif tier == "vip": discount += subtotal * 30 // 100 # a new tier? edit here if code == "WELCOME": discount += 500 # a new coupon? edit here if mugs >= 3: discount += mug_price # bug: 6 mugs should give 2 free # a new offer? edit here, and add parameters for it return max(0, subtotal - discount)print(total(6000, "premium", "WELCOME", 3, 1200)) # 3100print(total(9600, "premium", None, 6, 1200)) # 6480, and 5280 would be rightThe bad shape: the calculator knows every class
1/3Two shapes
The calculator asks each thing what it is, and then does the maths for it. The shapes are only bags of numbers.
uses
The good shape: the arrows turn around
1/4A contract in the middle
Shape says one thing: I can tell you my area. The calculator needs nothing else.
usesimplements
class Tier: def __init__(self, tier, percent): self.tier, self.percent = tier, percent def amount(self, cart): return cart["subtotal"] * self.percent // 100 if cart["tier"] == self.tier else 0class Coupon: def __init__(self, code, cents): self.code, self.cents = code, cents def amount(self, cart): return self.cents if cart["code"] == self.code else 0def total(cart, rules): # never edited again for a new rule left = cart["subtotal"] for rule in rules: left -= min(rule.amount(cart), left) return leftrules = [Tier("regular", 10), Tier("premium", 20), Tier("vip", 30), Coupon("WELCOME", 500)]cart = {"subtotal": 6000, "tier": "premium", "code": "WELCOME", "mugs": 3}print(total(cart, rules)) # 4300class ThreeForTwo: # new idea, new class def __init__(self, item, price): self.item, self.price = item, price def amount(self, cart): return cart.get(self.item, 0) // 3 * self.priceprint(total(cart, rules + [ThreeForTwo("mugs", 1200)])) # 3100Open for extension
- New features arrive as new code
- Through interfaces, composition, hooks, plugins, sometimes inheritance
- Behaviour can grow after the core was released
- A new requirement is usually a new class and a line of wiring
Not closed for modification
- Tested code is edited for every new kind
- Older behaviour may change by accident
- All variants must be tested again
- Teams meet in the same file
How it works
Who calls whom at run time
The engine holds a list of rules. It asks each the same question and does not care who answers. This is polymorphism: one call, many behaviours, chosen by the object that receives the call.
One quote
The same request, two designs
What grows when a kind is added
| If chain with n kinds | Contract with n kinds | |
|---|---|---|
| Branches in the core | n | 0 |
| Old code edited for kind n + 1 | The core, and often its callers | One line of wiring |
| Tests to run with suspicion | All n | The new one, plus the contract test |
| Places to read to understand one kind | The core | One class |
| Places to read to understand all | One method | n classes |
| Run-time work per quote | Up to n comparisons | n calls, unless rules are indexed |
A second picture
The chain and the charms
The wall shows why to have an extension point. The bracelet shows how extensions should behave towards the core and each other.
Two readings
Meyer's version and Martin's version
| Meyer, 1988 | Martin, 1996 | |
|---|---|---|
| Closed means | Finished, published, others use it | Its source is not edited for a chosen kind of change |
| Extended by | A descendant class of the finished class | Another implementation of an abstract interface |
| Reuses | The parent's code | The parent's contract |
| Risk | The child depends on inner details of the parent (fragile base class) | Too many interfaces, or the wrong ones |
| Today | Frameworks with template methods | The usual meaning in interviews and in SOLID |
If an interviewer asks for OCP, answer with the interface version and mention the first one. Meyer saw the problem, and inheritance was one tool to solve it. Extending a finished concrete class ties you to how it works inside. Implementing a small contract ties you to what it promises.
Both directions
Adding kinds or adding operations
The expression problem, on shapes
| Design | Add a kind (Hexagon) | Add an operation (perimeter) |
|---|---|---|
| Classes with methods | Cheap: one new class | Edit the interface and every class |
| One function per operation with a switch | Edit every function | Cheap: one new function |
| Visitor | Edit every visitor | Cheap: one new visitor |
Open functions (functools.singledispatch) | Register one more type | Write one more function |
Tools
Seven ways to leave a door open
Interfaces
Define the contract, implement freely. The base of all the others.
Strategy
Swap one algorithm. Our DiscountRule is a list of strategies.
Decorator
Add behaviour by wrapping: the same interface outside and inside.
Plugins
Discover and load extensions that the core's authors never saw.
Composition
Build big behaviour from small pieces instead of one big class.
Dependency injection
Hand the pieces in from outside, so that the core creates nothing by name.
Data
If only numbers differ, a table or a config file is the extension point. No class needed.
Judgement
When to build the socket
Should this become an extension point?
A second export format (CSV beside PDF) is requested. What do you do?
BreaksA plugin framework
- How
- Discovery, manifests, versions, a sandbox.
- Limit
- Weeks of work for two formats. The contract is guessed from too few examples and will be wrong.
- Choose when
- Only when other companies will write exporters.
WorksOne more if
- How
if fmt == "csv"in the export method.- Limit
- Fine for two. At four, every edit touches the others.
- Choose when
- One or two formats, no sign of more.
StrongExtract the interface now that there are two
- How
Exporter.write(report, out)with two classes, chosen from a small dict. Half an hour, and both can be tested alone.- Limit
- The contract comes from two examples. Keep it private so that it can still change.
- Choose when
- A second example shows you what really varies.
From if chain to rules in five safe moves
- 1
Pin it down with tests
Record what the old method returns for real carts. These tests must pass after every move.
- 2
Extract each branch
Give every branch its own function with the same parameters. Nothing else changes yet.
- 3
Find the common question
All functions take a cart and return cents. That sentence is the contract.
- 4
Make a list
Replace the chain with a loop over the functions, or over objects if they carry values.
- 5
Hand the list in
Move its creation out of the method. Now the method is closed, and the old tests prove that it behaves as before.
Neighbours
How it fits with the other principles
| Principle | Its part in OCP |
|---|---|
| Single responsibility | Each rule has one reason to change, so it can be a unit that you add |
| Liskov substitution | Every extension keeps the contract. Otherwise the core needs if isinstance again |
| Interface segregation | A small contract is easy to implement and rarely changes |
| Dependency inversion | Core and extensions both depend on the contract. This is how the arrows turn around |
| DRY | The loop, the limits and the receipt are written once, in the core |
| YAGNI | Says when not to do it |
Summary
The whole topic in one minute.
Find the axis that keeps changing, put a small contract on it, let the core call only the contract, and switch new pieces on in one place. A new discount is then a new class and one line of wiring.
You cannot be closed against everything. Choose the axis from evidence, usually the second or third change of the same kind. Until then a plain if is the better design.
In production the contract needs more than a method name: ordering, conflicts, limits, versions, a way to switch off, and one test that every extension must pass.
- Open for extension, closed for modification, along an axis that you chose.
- The core depends on a contract. The arrows from concrete classes end there.
- A contract is a method and its limits. An extension that breaks them opens the core again.
- Switch extensions on in one place. That line is allowed to change.
- Values differ: use data. Behaviour differs: use code.
- Wait for the second or third example, unless outsiders must extend you.
Sources
- Robert C. Martin: The Open-Closed Principle (C++ Report, 1996)
- Robert C. Martin: The Open Closed Principle (2014)
- Craig Larman: Protected Variation, The Importance of Being Closed (IEEE Software, 2001)
- Open-closed principle, history of both versions
- Philip Wadler: The Expression Problem (1998)
- Martin Fowler: Yagni
- Python Packaging: creating and discovering plugins
- Java: ServiceLoader
- pluggy
- Express: writing middleware
- webpack: plugins
- Kubernetes: scheduling framework
- Stripe: payment method integration options
- Factorio: data lifecycle of mods