Skip to content

Liskov Substitution

Medium — good to knowArchitecture

ELI5 — The Vibe Check

Liskov Substitution says if class B extends class A, you should be able to swap B in everywhere A is used without anything breaking. If your 'Electric Car' extends 'Car' but crashes when you call 'fillTank()', you've broken this rule.

Real Talk

The Liskov Substitution Principle states that objects of a subtype must be substitutable for objects of their base type without altering program correctness. Violations often manifest as subclass methods that throw exceptions, do nothing, or return unexpected results.

Show Me The Code

// Violation: Square inheriting Rectangle breaks LSP
class Rectangle {
  setWidth(w: number) { this.width = w; }
  setHeight(h: number) { this.height = h; }
}
class Square extends Rectangle {
  setWidth(w: number) { this.width = this.height = w; } // breaks Rectangle contract
}

When You'll Hear This

"This inheritance hierarchy violates Liskov Substitution." / "If you need to check the subtype before calling a method, LSP is broken."

Made with passive-aggressive love by manoga.digital. Powered by Claude.