Liskov Substitution Principle

No Change
adopt
First Added:June 24, 2026 Updated: July 2, 2026

Liskov Substitution Principle. The Liskov Substitution Principle (LSP) requires subtypes to honor the contract of their base type.

Summary

Garden stance: We adopt Liskov Substitution Principle for our estate.

When to use: Evaluate on a project when the capability clearly fits the requirement.

When to skip: When a simpler alternative already covers the need.

Details

Contract Checklist

ExpectationViolation signal
PreconditionsSubtype requires stricter inputs than the base
PostconditionsSubtype returns weaker guarantees
InvariantsSubtype breaks rules the base always maintained
ExceptionsSubtype throws errors callers did not expect
BehaviorSubtype ignores or no-ops base operations

Classic Examples

  • Square/rectangle: A square subtype of rectangle that breaks independent width/height setters
  • Read-only collection: A subtype that throws on add when the base promised mutability
  • Null returns: A subtype that returns null where the base never did

Safer Alternatives

  • Prefer composition and small interfaces over deep inheritance
  • Use Design Pattern Strategy or Adapter when behavior varies without an is-a relationship
  • Keep base contracts explicit in tests (contract tests for each implementation)

Common Failure Modes

  • Subclassing for reuse only (inherits API the child cannot honor)
  • Empty overrides that silently disable base behavior
  • instanceof or type switches in callers to paper over bad hierarchies
  • Framework base classes that encourage override hooks with unclear contracts

Related Garden Items