Codacoda
Back to Academy

coding principles

Liskov Substitution Principle

The Liskov Substitution Principle (LSP) requires that objects of a superclass shall be replaceable with objects of a subclass without altering the correctness of the program. If a function works with a base type, it must also work with any derived type. Violations occur when a subclass changes preconditions, postconditions, or invariants — for example, a Square subclass of Rectangle that breaks width/height independence. Adhering to LSP ensures polymorphism works safely and predictably.

Use Cases

  • Ensuring derived classes honor the contracts of their parent classes in a type hierarchy
  • Building collections of heterogeneous objects that can all be processed uniformly
  • Writing testable code where mock/stub implementations can replace real ones without surprises
  • Designing API response types where specialized responses extend a common base contract

Visualization

BEFORERectanglesetWidth()setHeight()SquaresetWidth()setHeight()AreaCalculatorcalculate(r)
Speed:1x
Square extends Rectangle. Seems logical — a square IS a rectangle in math. But does it hold in code?Step 1 / 7

Implementation

Output

Click "Run Code" to see output...