AlgoViz

Open/closed principle

medium 55 min

Code 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

0:00 / 4:49

Open/closed principle

1:03Reel

More reels

One idea each, a minute or less.

Play all in Bytesized Learning

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

  1. 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.

  2. 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.

  3. 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.

  4. 1998

    Philip Wadler names the expression problem: adding new types and adding new operations pull a design in opposite directions.

  5. 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.

  6. 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.

Step 1 of 4

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.

Noor, Lee and the wall

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.

Python
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 right
Before. Three kinds of customer, one coupon, one offer. Every new idea from marketing is an edit here.
Edit and run it in your browser

The bad shape: the calculator knows every class

AreaCalculator+ total(things): double- isRectangle(t): bool- isCircle(t): bool- isTriangle(t): boolRectangle+ width: double+ height: doubleCircle+ radius: double

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 same smell as the discounts: one class that depends on every variant.

The good shape: the arrows turn around

asks area()AreaCalculator+ total(shapes): double«interface»Shape+ area(): double

1/4A contract in the middle

Shape says one thing: I can tell you my area. The calculator needs nothing else.

usesimplements

Memory help: in the bad picture arrows fan out from the core. In the good one they all end in the contract.
Python
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)]))   # 3100
After. Each rule is a small object with one method. The engine does not know any of them by name.
Edit and run it in your browser

Open 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 last participant did not exist when the engine was written. The engine calls it anyway.

The same request, two designs

What grows when a kind is added

If chain with n kindsContract with n kinds
Branches in the coren0
Old code edited for kind n + 1The core, and often its callersOne line of wiring
Tests to run with suspicionAll nThe new one, plus the contract test
Places to read to understand one kindThe coreOne class
Places to read to understand allOne methodn classes
Run-time work per quoteUp to n comparisonsn calls, unless rules are indexed
Two rows speak for the if chain. Reading everything at once is easier in one method. And the contract does not make the program faster: it makes the change smaller.

A second picture

The chain and the charms

Asha's bracelet

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, 1988Martin, 1996
Closed meansFinished, published, others use itIts source is not edited for a chosen kind of change
Extended byA descendant class of the finished classAnother implementation of an abstract interface
ReusesThe parent's codeThe parent's contract
RiskThe child depends on inner details of the parent (fragile base class)Too many interfaces, or the wrong ones
TodayFrameworks with template methodsThe 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

DesignAdd a kind (Hexagon)Add an operation (perimeter)
Classes with methodsCheap: one new classEdit the interface and every class
One function per operation with a switchEdit every functionCheap: one new function
VisitorEdit every visitorCheap: one new visitor
Open functions (functools.singledispatch)Register one more typeWrite one more function
So ask which grows faster. Discounts grow in kinds: use classes. A compiler's syntax tree is stable in kinds and grows in operations: use visitors or a switch. With a sealed type and an exhaustive switch, the compiler even lists the places to edit.

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?

Exception: when people outside your team must extend it, the extension point is itself the feature. Build it from the start.

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. 1

    Pin it down with tests

    Record what the old method returns for real carts. These tests must pass after every move.

  2. 2

    Extract each branch

    Give every branch its own function with the same parameters. Nothing else changes yet.

  3. 3

    Find the common question

    All functions take a cart and return cents. That sentence is the contract.

  4. 4

    Make a list

    Replace the chain with a loop over the functions, or over objects if they carry values.

  5. 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

PrincipleIts part in OCP
Single responsibilityEach rule has one reason to change, so it can be a unit that you add
Liskov substitutionEvery extension keeps the contract. Otherwise the core needs if isinstance again
Interface segregationA small contract is easy to implement and rarely changes
Dependency inversionCore and extensions both depend on the contract. This is how the arrows turn around
DRYThe loop, the limits and the receipt are written once, in the core
YAGNISays when not to do it
See SOLID for all five on one page, and Strategy for the pattern used most here.

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