Skip to content
Tutorials Center
My learning

Topics

Lesson 7 of 57 ยท Design Principles

Liskov Substitution Principle

Learn the Liskov Substitution Principle: behavioral subtyping, the square and rectangle trap, contracts, and a contract test that catches violations.

The Liskov Substitution Principle (LSP) is the "L" in SOLID. It says that if code works with a base type, it must keep working when you hand it any subtype, without knowing which one it got. Barbara Liskov described the idea in the 1980s, and the short version is this: a subclass must be usable anywhere its parent is expected, and nobody should be surprised by the result.

This sounds like something the compiler already checks, but it does not. A compiler only checks that the method names and types line up. LSP is about behavior: what a method promises, what it needs, and what it leaves untouched. A class can compile as a perfect subtype and still break every caller that trusts the parent's promises. If you have not read the overview yet, start with SOLID at a Glance, and keep the Open/Closed Principle in mind, because LSP is what makes polymorphic extension safe.

What substitutable means

Same promises A subtype keeps every promise the parent made.
Not stricter in It never demands more from callers.
Not weaker out It never delivers less than the parent did.
Same invariants Rules that always held for the parent still hold.

Callers should not need an if that asks "which subclass is this?"

1 / 2

Behavioral subtyping

"Is-a" in everyday speech is not the same as "is-a" in code. A penguin is a bird, but if your Bird class has a fly() method that callers rely on, a Penguin subclass cannot honor it. The real question is never "is this a kind of that thing in the world?" but "can this object stand in for the parent, with every caller still correct?"

A subtype is behaviorally substitutable when it respects the parent's contract. A contract has three parts:

  • Preconditions are what a method needs before it runs, such as "the amount is positive". A subclass may weaken a precondition (accept more inputs) but must never strengthen it (reject inputs the parent accepted).
  • Postconditions are what a method guarantees afterward, such as "the returned list is sorted". A subclass may strengthen a postcondition (promise more) but must never weaken it.
  • Invariants are facts that stay true for the object's whole life, such as "balance is never negative". A subclass must preserve every invariant of the parent.

A handy way to remember the direction: a subtype should be contravariant in what it accepts and covariant in what it returns. It can be more forgiving going in and more generous coming out, never the reverse.

There is a further rule about errors. A subclass should not throw new kinds of exceptions that callers of the parent never expect, because those callers have no handler for them.

The classic trap: square and rectangle

In geometry a square is a rectangle, so it feels natural to write class Square extends Rectangle. Here is that design, with a function written against the parent. The function sets the width to 5 and the height to 4 and then asks for the area; for any rectangle that must be 20.

JS The square that is not a rectangle

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The Square compiles (or, in JavaScript, runs) and has every method of Rectangle, yet stretchTo5By4 returns 16 instead of 20. The parent made an implicit promise: setting the width does not change the height. Square broke that postcondition to protect its own invariant (all sides equal). Both rules are reasonable; they simply cannot live in one hierarchy with mutable setters.

You have three honest ways out. Make the shapes immutable, so there are no setters to disagree about. Stop modeling a square as a rectangle and share only what is really common, such as an area() method. Or give each type its own operations, with Rectangle.resize(w, h) and Square.resize(side). The fix is almost never "add an instanceof Square check inside stretchTo5By4", because that turns every caller into a special-case handler and defeats polymorphism.

Writing the contract down as a test

A contract only protects you if it is checked. A contract test is a set of checks written against the parent's promises and run against every subclass. If a new subclass fails a parent-level test, it violates LSP, and you find out in seconds instead of in production.

JS A contract test that catches the violation

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The same test file can be reused for every future subclass. In a real project this lives in your test suite as a shared "behaves like a Rectangle" helper, and each subclass test calls it.

A hierarchy that respects LSP

Now redesign so that the types share only what is true for all of them. Both shapes can report an area and a description. Neither allows mutation, so no caller can be surprised by a setter.

JS A substitutable design

Press Run (or Ctrl + Enter) to see the console output here.

No output.

totalArea knows nothing about the concrete classes, and it never needs to. That is the goal. Note also the constructors: each subclass checks its own inputs, but none of them rejects values that the shared Shape contract would accept, because Shape itself has no constructor input to protect.

LSP in real languages

In Java and C++ the type system adds some help and some traps. A Java method that overrides another cannot narrow its parameter type (that would be an overload, not an override) and may only return a more specific type, which matches the covariance rule above. Throwing a new checked exception is a compile error, but throwing a new RuntimeException is not, so the language will not protect you there.

Java
class FileStore {
    void save(String name, byte[] data) { /* writes to disk */ }
}

class ReadOnlyFileStore extends FileStore {
    @Override
    void save(String name, byte[] data) {
        throw new UnsupportedOperationException("read-only"); // LSP violation
    }
}

Any code that receives a FileStore and calls save now has a hidden failure path. The fix is to split the abstractions, so that ReadableStore and WritableStore are separate roles (this is exactly what the next lesson, Interface Segregation, is about). In Python and JavaScript there is no compiler at all, so contract tests and clear documentation are your only guard.

When you are unsure about a subclass, ask: "If I replaced every use of the parent with this child, would any existing test or caller need to change?" If yes, the inheritance is probably the wrong tool, and composition usually fits better.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does the Liskov Substitution Principle require of a subclass?

    LSP is about behavior. Code written against the parent type must keep working correctly when it receives any subtype.
  2. 2. Which change to a method in a subclass is allowed under LSP?

    A subclass may weaken preconditions (accept more) and strengthen postconditions (promise more), but not the opposite.
  3. 3. Why does Square extending a mutable Rectangle break LSP?

    Code written for rectangles expects setWidth to leave the height alone. Square must change both sides to stay square, so it violates that postcondition.
  4. 4. What is a contract test?

    A contract test encodes the base type's behavior once, so any subclass that fails it is shown to violate LSP.

Summary

  • LSP means every subtype must be safely usable wherever its parent is expected.
  • It is about behavior (preconditions, postconditions, invariants), not just method signatures.
  • Subclasses may accept more and promise more, never the reverse.
  • Warning signs: "not supported" exceptions, empty overrides and instanceof checks in callers.
  • Contract tests run the parent's promises against every subclass and catch violations early.
  • When "is-a" does not hold behaviorally, split the abstraction or use composition.

Next lesson: Interface Segregation Principle.