Part 2 of 6 · 1 min read
The idea
A substitute must behave like the original.
Think of a spare tyre. A spare is a good one when the car drives the same with it fitted. If the car pulls to the left, or the wheel only fits some cars, then it is a tyre in name only.
Barbara Liskov defined it in 1988 for types. If a program is written in terms of a type T, and swapping any T object for an S object leaves the program's behaviour unchanged, then S is a proper subtype of T. This is the Liskov substitution principle. The important word is behaviour. A subclass that compiles is not enough. It must act in a way that callers of the parent can live with.
CA shows a good case first. A License class has a method calcFee(). Two subclasses, PersonalLicense and BusinessLicense, calculate the fee in different ways. A billing program calls calcFee() and does not care which kind it holds. Both can take the parent's place, so the design is sound.
Liskov substitution principle
The Liskov substitution principle says that code written for a parent type must keep working, without any type checks, when it receives any subclass.
Example: a billing method that accepts a License and works for personal and business licences alike.
Check yourself:
1. What must stay unchanged when a subclass replaces its parent?
2. Why is "it compiles" not enough?
3. Why does the License example conform?