Liskov substitution (LSP)
medium 55 minAn object of a subtype must be usable wherever the supertype is expected, with no surprise for the caller.
Video lesson · Chapter 1 of 6
Make a prediction
Liskov substitution
1:05Reel
More reels
One idea each, a minute or less.
Spot it: Liskov substitution
0:33Reel
Theory
Read or listen first. About 3 min.
What it is
The Liskov substitution principle (LSP) says: if code works with a type, it must also work with every subtype of it, without knowing which one it got. It is the L in SOLID.
It is about behaviour, not about method names. A type is a set of promises: what it accepts, what it gives back, which errors it may raise, what is always true about it, and how it may change. Together they are its contract. A subtype keeps the whole contract. It may promise more. It may not ask for more, and it may not give less.
The compiler checks the names and the types. Nobody checks the rest for you. This is why a broken substitute compiles, looks tidy in review, and fails later, in code that did nothing wrong.
Why it exists
Polymorphism is built on it. A caller holds a Store and calls save. If some stores silently forget, every caller must ask which store this is, and the benefit of the common type is gone.
The damage appears far from its cause. The subclass looks right, the caller looks right, and only the pair is wrong. Such bugs give wrong results instead of an error, and tests with the original class all pass.
The other principles lean on it. Open/closed says that new kinds arrive without edits. That is only true if the new kind keeps the promises. Otherwise the core needs if isinstance again.
A short history
1987
Barbara Liskov gives the keynote Data Abstraction and Hierarchy at the OOPSLA conference and describes a subtype by substitution: the behaviour of a program does not change when the subtype's objects are used instead.
1988
Bertrand Meyer's Object-Oriented Software Construction gives a rule for redefined methods: a precondition may only become weaker, a postcondition only stronger. Martin quotes it in 1996.
1994
Barbara Liskov and Jeannette Wing publish A Behavioral Notion of Subtyping. It makes the idea precise and adds the history rule: new methods may not allow changes that the supertype rules out.
1996
Robert C. Martin brings it to C++ programmers in the C++ Report. The column shows Rectangle and Square, and a real case: a persistent set that refuses most elements.
2014
PEP 484 gives Python type hints. Checkers such as mypy now refuse an override whose signature is unsafe, and their messages name the Liskov principle. They see signatures, not behaviour.
Words to know
- Supertype, subtype
- The type the caller names, and the type of the object that really arrives.
- Contract
- Everything a caller may rely on, written or not.
- Precondition
- What must be true before a call. The caller's duty.
- Postcondition
- What is true after the call. The method's duty.
- Invariant
- What is true about the object between all calls.
- History rule
- How the state may change over time. A subtype may not allow a change that the supertype excludes.
- Behavioural subtype
- A subtype that keeps the contract, and not only the method list.
- Refused bequest
- A subclass that does not want what it inherits: empty or throwing overrides.
- Covariant, contravariant
- A result may get more specific, a parameter may get more general. See covariance and contravariance.
- Contract test
- One set of tests that every implementation must pass.
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.
Write the promises. What may callers rely on?
Understand it
Start here
The substitute at the school crossing
Noor guards the crossing in front of the school. Three promises hang on a board: any child may cross, the cars stop, and they stay stopped till all children are over. The children do not look at the face of the guard. They look at the coat, and then they walk.
Frames 3 to 6 are the four ways to break substitution. Frame 8 is the usual repair: do not wear the coat.
The classic
A square that calls itself a rectangle
In geometry a square is a rectangle. So Square extends Rectangle looks right. But a Rectangle object makes a promise that geometry does not: setting the width leaves the height alone. A square cannot keep that.
class Rectangle: def __init__(self, w=0, h=0): self.w, self.h = w, h def set_width(self, w): self.w = w def set_height(self, h): self.h = h def area(self): return self.w * self.hclass Square(Rectangle): def set_width(self, w): self.w = self.h = w # also changes the height def set_height(self, h): self.w = self.h = hdef resize(r: Rectangle): r.set_width(5) r.set_height(10) return r.area() # 50, says the contractprint(resize(Rectangle())) # 50print(resize(Square())) # 100resize contains no mistake.The bad shape: inheriting a promise you cannot keep
1/4A rectangle
Two independent sides. Nobody wrote the promise down, but every caller uses it.
usesextends (is a)
The good shape: promise only what all can keep
1/3A small promise
Every shape can tell its area. That is all the report needs.
usesimplements
How the wrong answer is made
The rules
What a subtype may and may not do
| Part of the contract | A subtype may | A subtype may not | At the crossing |
|---|---|---|---|
| Precondition | Accept more | Demand more | No season ticket |
| Postcondition | Promise more | Promise less | Till all are over |
| Invariant | Add its own | Drop an inherited one | The sign is up while children cross |
| Errors | Raise fewer, or more specific ones | Raise kinds that callers cannot expect | No plate that says closed |
| History | Change in ways the supertype allows | Allow new kinds of change | A red light does not become green early |
| Signature | More general parameters, more specific result | The reverse, or a new required parameter | Same gestures |
Keeps the contract
Dog extends Animal, andspeak()barksSedan extends Car, anddrive()drivesLogStorekeeps text in a list instead of a table- A list that also counts its reads
Breaks it
Penguin extends FlyingBird, andfly()throwsSquare extends Rectangle, andsetWidth()changes the height- A store that trims spaces from what you saved
- A cache that returns yesterday's value as if it were new
May S stand in for T?
The history rule as a picture
Store has the first three arrows. An expiring store adds the fourth. Every single method still looks right, but a caller who saved and then loads after lunch is surprised.A second example
Birds, and what we really promise
A Bird with fly() works for sparrows and eagles. Then a penguin joins. It has feathers and lays eggs, so Penguin extends Bird. What goes into its fly()?
What should Penguin.fly() do?
BreaksThrow an exception
- How
raise Exception("Penguins can't fly")- Limit
- A loop over birds stops at the penguin. The sparrow after it never flies.
- Choose when
- Never as an override of a promised method.
BreaksDo nothing, or waddle
- How
- An empty body, or a message about walking.
- Limit
- No error at all. A caller that plans a route by air now has a penguin on the ground.
- Choose when
- Only if the contract says: may do nothing.
WorksAsk first
- How
if bird.can_fly(): bird.fly()- Limit
- Every caller must remember the question. One forgets.
- Choose when
- Capabilities that are only known at run time.
StrongDo not promise flight for all birds
- How
Birdpromisesmove(). Flying is a role of its own that only flyers have.- Limit
- Callers must say which of the two they need. That is a gain.
- Choose when
- The set of abilities is known when you write the class.
Birds by what they can do
1/4What all birds do
They move. Bird promises that and no more.
extends (is a)implements
from abc import ABC, abstractmethodclass Bird(ABC): @abstractmethod def move(self) -> str: ...class Flyer(Bird): @abstractmethod def fly(self) -> str: ... def move(self): return self.fly()class Sparrow(Flyer): def fly(self): return "sparrow flies"class Penguin(Bird): def move(self): return "penguin waddles"class Ostrich(Bird): def move(self): return "ostrich runs"def parade(birds: list[Bird]): return [b.move() for b in birds]def race_by_air(flyers: list[Flyer]): return [f.fly() for f in flyers]print(parade([Sparrow(), Penguin(), Ostrich()]))print(race_by_air([Sparrow()]))Looks like a duck
The duck test, and where it stops
If it looks like a duck, swims like a duck and quacks like a duck, it probably is a duck. For programmers the saying means: ask what an object does, not what it is called. LSP agrees, with one addition: the behaviour must be the one that the callers expect.
| Object | Has squeeze() and float() | Callers get | Substitutable for a bath duck? |
|---|---|---|---|
| Rubber duck | Yes | A squeak | Yes |
| Toy duck with a sinking weight | Yes | It sinks | For the shelf yes, for the bath no |
| Duck bomb | Yes | An explosion | No |
Four questions for a review
Signatures
Does it accept at least the same arguments?
Results
Is what comes back at least as good as promised?
Errors
Does it raise only what the supertype announced?
Invariants
Is everything that was always true still always true, also after its new methods?
Smells
Signs of a violation in code
| Sign | Looks like | What it says |
|---|---|---|
| Type checks in the caller | if isinstance(b, Penguin) | The caller works around a subtype |
| Empty override | def write(self, text): pass | The scarecrow: the promise is not kept, silently |
| Not supported | throw new UnsupportedOperationException() | The supertype promises too much |
| Odd null checks | if (result != null) where the contract says never null | Some subtype returns less |
| Extra setup | Call open() first, but only for this one | A stronger precondition |
| Comments such as: do not use with | # not for RemoteStore | Somebody found out already |
| Tests that skip one class | if cls is not ReadOnly | The contract test says no, and was told to be quiet |
Repair
Five ways out
Shrink the supertype
Promise only what all can keep.
Shape.area()without setters.Split it
ReaderandStore. Callers name the one they need. See interface segregation.Compose
A stack has a list and shows push and pop only. See inheritance vs composition.
Make it immutable
Without mutators, many false relatives become true ones.
Weaken the contract on purpose
Write: may fail with
StoreDown. Then all callers know, also the old ones, and you must tell them.
Summary
The whole topic in one minute.
A subtype may accept more, promise more and offer more. It may not demand more, deliver less, raise surprises or forget what the supertype keeps. Is-a in daily language proves nothing: ask what callers rely on.
Most violations are repaired by a smaller promise: split what some cannot do into its own type (Reader beside Store, Shape without setters). Then nobody can pass the wrong object, because it does not compile.
In production the contract is kept by tests that every implementation runs, by wrappers that translate errors, and by care with equality, mutability and versions. Type checkers help with signatures only.
- Subtypes keep the contract of the supertype, so callers need not know them.
- Take more, give more. Never demand more, never deliver less.
- Same method names are not enough. Is-a in daily language is not enough.
- History counts: new methods may not allow changes the supertype excludes.
- An override that throws, does nothing or narrows is a sign that the supertype promises too much.
- Compilers see signatures. Contract tests see behaviour.
Sources
- Liskov and Wing: A Behavioral Notion of Subtyping (1994)
- Robert C. Martin: The Liskov Substitution Principle (C++ Report, 1996)
- Liskov substitution principle, history and rules
- Java: Stack
- Java: Properties
- Java: Collection, optional operations
- Java: IdentityHashMap
- Java: java.sql.Timestamp
- .NET: Stream.CanSeek
- Python: io
- Go: package io, Writer
- mypy: incompatible overrides
- TypeScript: strictFunctionTypes