Card 01/ 09
Liskov Substitution: A Subtype Must Keep Its Parent's Promises
Code written for any bird should not crash when it is handed an ostrich.
The Liskov substitution principle says that wherever code expects an object of some class, it must be able to receive an object of any subclass and still work correctly. A subtype is any class that can stand in for another: a subclass, or a class implementing an interface. This card explains why that is a rule about behaviour, not about having the right method names.
Barbara Liskov introduced the idea in a 1987 conference keynote, "Data Abstraction and Hierarchy". Her point was that inheritance is only safe when the child can be substituted for the parent without the caller noticing. A language checks that the method exists. It cannot check that the method still does what the caller relies on.
Take a Bird class with a fly method, and a migrate function that calls fly on every bird it is given. A Sparrow subclass flies. Then someone adds Ostrich, which is certainly a bird, and overrides fly to raise an error, because ostriches cannot fly. Every type checker accepts this. migrate crashes the first time a flock contains an ostrich.
The diagram shows where the damage lands. Ostrich is fine on its own. The failure appears in migrate, code that was written correctly against Bird and that nobody changed. That is what makes substitution failures hard to find: the bug is in one class and the crash is in another.
An agency driver is a fair picture. If you hire any licensed driver, you expect them to drive your car the way drivers do: forward with the accelerator, stop with the brake. A driver who refuses motorways breaks that expectation, even though they hold the licence. The analogy breaks in one place: a human driver can tell you why they refused before you set off, while a subtype raises its error in the middle of the journey, with no warning.
The principle asks you to model the promise correctly. If not every bird flies, Bird should not promise fly.
← → move through sections and cards