Liskov Substitution
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."
Related Terms
Inheritance
Inheritance lets a class take on all the properties and behaviors of another class.
Open-Closed
Open-Closed means your code should be open for adding new features but closed for editing old working code.
Polymorphism
Polymorphism means the same method call can do different things depending on which object it's called on. Call 'speak()' on a Dog and you get a bark.
SOLID (SOLID)
SOLID is five rules for writing code that doesn't turn into a nightmare over time. Each letter stands for a different rule.