Liskov Substitution Principle
Code written against a base type must keep working when it is handed any subtype. A subtype may promise more, but never less.
Overview
The Liskov Substitution Principle (LSP) is the L in SOLID, and the only one named after its author. Barbara Liskov stated it in a 1987 OOPSLA keynote, Data Abstraction and Hierarchy: if for every object of type S there is an object of type T such that any program written for T behaves the same when given the S object, then S is a subtype of T. Liskov and Jeannette Wing made it precise in 1994 as the subtype requirement: any property provable about objects of the supertype should also hold for objects of the subtype.
The 1996 paraphrase by Robert C. Martin is the one interviewers expect: functions that use references to base classes must be able to use objects of derived classes without knowing it. The word that matters is behavior. A subclass that compiles is not automatically a subtype. It is a subtype only if callers of the base class cannot tell the difference.
So the principle has three statements, each building on the last. In 1987, Liskov's Data Abstraction and Hierarchy gave the substitution property: programs written for T behave the same with S. In 1994, Liskov and Wing's A Behavioral Notion of Subtyping gave the subtype requirement: properties provable for T hold for S. In 1996, Martin's C++ Report column gave the working rule: functions using base-class references work with derived classes without knowing it. The classic example shows what 'without knowing it' means in code.
Rectangle and Square
A square is a rectangle in geometry, so it is tempting to write class Square(Rectangle). A square has to keep its sides equal, so setting the width also sets the height. That breaks code written for rectangles, which expects the two sides to change independently.
stretch is correct for every Rectangle and wrong for every Square. Martin's summary: a square may be a rectangle, but a Square object is not a Rectangle object, because its behavior is different. In object-oriented design the is-a relationship is about behavior clients can observe, not about geometry.
Interview questions
- What is the Square-Rectangle problem and how do you fix it?
- What are the formal rules of the Liskov Substitution Principle?
- How do you test for LSP violations?
- Is a read-only collection that throws on add() an LSP violation?
- How does LSP relate to the Open/Closed Principle?
Sign up free to read the full topic
More Low-Level Design topics
Start free on Cariara · Coding problems · System design studio