Table of Contents

Liskov Substitution Principle (LSP)

Variants and Alternative Names

Context

Principle Statement

“Subtypes must be substitutable for their base types.”1)

Description

Object-oriented programming languages permit the derivation of subtypes from base types, and subtype polymorphism allows the passing of an object of a subtype where ever an object of the supertype is specified. Suppose P and Q are types (i.e. classes or interfaces) and Q is derived from P (so Q is the subtype and P is the base type or supertype). A method m requiring a parameter of type P can be called with objects of type Q because every object of type Q is also an object of type P. This is always true as typically object-oriented programming languages are constructed in that way.

The programming language does not enforce that the subtype behaves like the supertype. Method m may work with an object of type P, but not with an object of type Q. LSP demands that a subtype (Q in the example) has to be constructed in a way that it behaves like the supertype if it is called through the supertype interface. Q may have further methods and it may do additional things not observable by m but m shall be able to safely assume that its parameter behaves like an object of type P with respect to all observable state.

Rationale

Let P and Q be types and Q a subtype of P. If LSP is not adhered to, there is an operation accessible through the interface of P which behaves differently when called on Q. So code which is written in terms of P will not expect the behavior and will not work as desired.

Strategies

Caveats

See section contrary principles.

Origin

Barbara Liskov: Data abstraction and hierarchy

Evidence

Relations to Other Principles

Generalizations

Specializations

Contrary Principles

Complementary Principles

Principle Collections

OOD Principle Language
General Principles
ML KISS MIMC DRY GP RoE
Modularization Principles
MP HC ECV
Module Communication Principles
TdA/IE LC DIP
Interface Design Principles
EUHM PLS UP
Internal Module Design Principles
IH/E IAP LSP PSU

Examples

Description Status

Incomplete

Further Reading

Discussion

Discuss this wiki article and the principle on the corresponding talk page.

1)
Robert C. Martin: Agile Software Development, Principles, Patterns, and Practices, p. 111