Why your code breaks when you swap a parent class for its child

Why your code breaks when you swap a parent class for its child
Image: Intellect (generated)

In short: The Liskov substitution principle dictates that a subclass must be fully interchangeable with its parent without disrupting program logic. If your software fails when a child object replaces a base class, you have likely violated this fundamental rule of object-oriented design, leading to fragile and unpredictable system behavior.

Introduced by Barbara Liskov in 1987, the Liskov substitution principle (LSP) defines strong behavioral subtyping. It asserts that if a program relies on a base type, it should function identically if that type is swapped for a subtype. This is a semantic requirement, not just a syntactic one, ensuring that the expected properties of the original class remain intact throughout the program's execution.

The principle imposes strict constraints on how subtypes interact with contracts. Specifically, preconditions cannot be made more restrictive, and postconditions cannot be relaxed. Furthermore, invariants must be maintained. A critical addition by Liskov and Wing in 1994 was the history constraint, which prevents subtypes from introducing state changes that were impossible in the supertype. This rule specifically forbids treating a mutable object as a subtype of an immutable one, a scenario that earlier definitions by Bertrand Meyer failed to address.

While LSP is theoretically undecidable—meaning a compiler cannot always verify if a subtype will satisfy every property of its parent—it serves as a vital guide for class hierarchy design. A classic example of a violation is defining a square as a subtype of a rectangle. While a square is geometrically a rectangle, the behavioral expectations of a rectangle—where width and height can be modified independently—are broken when a square enforces a constraint that both dimensions must remain equal.

LSP is the 'L' in the SOLID design acronym. By adhering to these rules, developers ensure that their class hierarchies are robust and that inheritance is used to extend functionality rather than subvert the logic of existing components. It forces a deeper consideration of how objects behave, rather than simply focusing on the superficial 'is-a' relationships that often lead to flawed software architectures.

Opens the Intellect+ feed with this card first. Swipe up for the next one.

Sources

To cite this card, link to https://intellectplus.co.uk/app/technology-liskov-substitution-principle.

How we source, check and correct cards: Editorial standards.

General information, not professional advice. Spotted an error? Flag the card or see corrections and complaints.

Intellect Plus is a visual educational discovery platform for exploring fascinating facts and ideas. Brain Food, Not Brain Rot. What is Intellect Plus?

Related

Finding something worth knowing…