Liskov Substitution Principle

The Liskov substitution principle in SOLID: a subclass must work anywhere its parent does, keeping every promise the parent makes.

  • 9 cards
  • 5 questions
  • About 17 min
  • Beginner to Intermediate
Share

The Liskov substitution principle is the L in SOLID. It says that code written for a parent class must keep working when it is handed any subclass. Having the right method names is not enough; the subclass has to behave the way the caller was promised.

The topic starts with that promise and a bird hierarchy that breaks it, in Python, Java and TypeScript. It then makes "behaves the way it was promised" precise with three rules about inputs, results and invariants, and refactors the hierarchy so that no bird is asked to do what it cannot. Two examples follow: a square that is not a rectangle in code, and Java's unmodifiable list, a deliberate breach in the standard library.

The last cards show the clue that substitution is already broken, a type check in the caller, and give you a savings account to fix.

By the end you can predict what a broken subtype does to its caller, say what a subtype may change, and fix a hierarchy by changing the abstraction rather than the subclass.

Contents

9 cardsnot started