Liskov Substitution Principle
You'll learn to
- -State the Liskov Substitution Principle (LSP) in plain words: a subclass must keep every promise its base class makes
- -Define precondition, postcondition and invariant, and use them to spot a violation
- -Explain why Square extending Rectangle fails by running it and seeing 16 instead of 20
- -Fix a broken hierarchy by changing the design instead of overriding the problem away
Tip: the highlighter is on - just select any text below to mark it. Use the highlighter button up top to change color or turn it off. Highlights are saved on this device only. Log in to save them to your account instead.
The Liskov Substitution Principle (LSP) says that code written against a base class should keep working, unchanged, when it is handed any subclass instead. No surprises and no broken assumptions. It is named after Barbara Liskov, who stated it in the 1980s, and it is the third of the five SOLID principles.
An Analogy: The Rental Car Contract
When you rent "a car", the agency promises certain things: it starts when you turn the key, it carries five people, and it has a boot for the luggage. You plan your trip around those promises. If the agency hands you a two-seat sports car labeled "car", your family trip fails, even though a sports car really is a kind of car.
- -The advertised promises are the contract of the base class: what it guarantees to anyone who uses it.
- -Whatever vehicle you are handed is a subclass object.
- -Your trip plan is the code that uses the base class.
- -A vehicle that cannot carry five people is a subclass that breaks a promise, which is an LSP violation.
Three Words for Promises
A precondition is what a method requires from its caller before it runs, such as "the amount must be positive". A postcondition is what the method promises when it finishes, such as "the balance went down by exactly that amount". An invariant is a fact that must always be true about an object, such as "a balance is never negative". LSP says that a subclass may ask no more than its base class asked, must deliver at least what its base class delivered, and must keep every invariant.
The Square-Extends-Rectangle Trap
In geometry a square is a rectangle whose width equals its height, so extending Rectangle looks natural. But a Rectangle makes an unwritten promise: setting the width changes only the width. Run the code below. A function resizes a shape to 5 by 4 and reports its area.
A Rectangle gives 20, as the function expects. A Square gives 16, because the second call quietly changed the width back to 4. The Square is mathematically a rectangle but behaviorally not one, because it breaks a promise the Rectangle made. Any code that trusts the Rectangle contract is now wrong the moment someone passes it a Square.
Another Way to Break the Promise: Asking More of the Caller
LSP violations are not only about geometry. A very common one is a subclass that rejects inputs the base class accepted, which is a stronger precondition. Here a gift card refuses large payments that a plain Payment would take.
The checkout code was written for Payment and now fails with a GiftCardPayment. The mirror image is a subclass that returns something weaker than the base class promised, such as a vague result or fewer fields, which weakens the postcondition.
How to Fix a Broken Hierarchy
- -Stop forcing the is-a relationship. Let Square and Rectangle both implement a small Shape interface with area(), and give each its own way to be built, so that nobody can change one side of a square on its own.
- -Make the objects immutable. A shape you cannot change after creating it cannot break the promise that a setter changes only one side.
- -Split the base class by capability. A Bird that promises fly() cannot sensibly have a Penguin subclass. Make Bird the general type and add a separate FlyingBird type for the animals that can fly.
A subclass that overrides a method just to throw "not supported", like RubberDuck.fly() raising an error, is one of the clearest LSP violations you can point to on a whiteboard. The subtype cannot honor the base type's contract at all.
A colleague proposes making Penguin extend Bird, where Bird has a fly() method. What is the LSP concern?
"That seems fine - a penguin is technically a bird."
"Biologically yes, but if Bird's contract includes fly(), any code that calls bird.fly() on a list of Birds would break or need special-casing for Penguin. That's an LSP violation - Penguin can't honor the full Bird contract. I'd either move fly() out of Bird into a separate FlyingBird interface/capability, or model Penguin so it never has to override fly() with an exception."
What does the Liskov Substitution Principle require?
Discussion0
Join the Discussion
Sign in to leave comments, reply to others, or like insights.
No comments yet. Be the first to start the thread!