AlgoViz

Liskov substitution (LSP)

medium 55 min

An 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

0:00 / 5:06

Liskov substitution

1:05Reel

More reels

One idea each, a minute or less.

Play all in Bytesized Learning

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

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

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

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

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

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

Step 1 of 4

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.

Noor's substitutes
The guard promisesAny childCars stopTill all are overSTOP

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.

Python
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()))      # 100
Before. Nothing crashes. The answer is simply wrong, and resize contains no mistake.
Edit and run it in your browser

The bad shape: inheriting a promise you cannot keep

Rectangle# width: int# height: int+ setWidth(w)+ setHeight(h)+ area(): int

1/4A rectangle

Two independent sides. Nobody wrote the promise down, but every caller uses it.

usesextends (is a)

A class diagram cannot show a broken promise. You must ask about each inheritance arrow.

The good shape: promise only what all can keep

AreaReport+ total(shapes): int«interface»Shape+ area(): int

1/3A small promise

Every shape can tell its area. That is all the report needs.

usesimplements

Circle and Triangle can follow. This is open/closed, and it works because every shape keeps the contract.

How the wrong answer is made

The rules

What a subtype may and may not do

Part of the contractA subtype mayA subtype may notAt the crossing
PreconditionAccept moreDemand moreNo season ticket
PostconditionPromise morePromise lessTill all are over
InvariantAdd its ownDrop an inherited oneThe sign is up while children cross
ErrorsRaise fewer, or more specific onesRaise kinds that callers cannot expectNo plate that says closed
HistoryChange in ways the supertype allowsAllow new kinds of changeA red light does not become green early
SignatureMore general parameters, more specific resultThe reverse, or a new required parameterSame gestures
Memory help for the first two rows: take more, give more.

Keeps the contract

  • Dog extends Animal, and speak() barks
  • Sedan extends Car, and drive() drives
  • LogStore keeps text in a list instead of a table
  • A list that also counts its reads

Breaks it

  • Penguin extends FlyingBird, and fly() throws
  • Square extends Rectangle, and setWidth() 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

A 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
Bird promises move(). 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

«interface»Bird+ move(): String

1/4What all birds do

They move. Bird promises that and no more.

extends (is a)implements

Model behaviour that callers need, and not the animal kingdom.
Python
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()]))
Every bird moves. Only flyers are asked to fly, and the type says so.
Edit and run it in your browser

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.

ObjectHas squeeze() and float()Callers getSubstitutable for a bath duck?
Rubber duckYesA squeakYes
Toy duck with a sinking weightYesIt sinksFor the shelf yes, for the bath no
Duck bombYesAn explosionNo
The middle row is the important one. Substitutable is a statement about a contract. A small contract (looks nice) accepts more objects than a large one (looks nice and floats).

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

SignLooks likeWhat it says
Type checks in the callerif isinstance(b, Penguin)The caller works around a subtype
Empty overridedef write(self, text): passThe scarecrow: the promise is not kept, silently
Not supportedthrow new UnsupportedOperationException()The supertype promises too much
Odd null checksif (result != null) where the contract says never nullSome subtype returns less
Extra setupCall open() first, but only for this oneA stronger precondition
Comments such as: do not use with# not for RemoteStoreSomebody found out already
Tests that skip one classif cls is not ReadOnlyThe 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

    Reader and Store. 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