The Liskov Substitution Principle (LSP) says that a child class must be usable wherever its parent class is expected without breaking the application. It is not enough for the child to have the right method names: its behavior must keep the parent’s promises. section 3.4.3
A substitute who breaks the rules
A coach sends a goalie into midfield. The player looks like a valid substitute, but behaves like a goalie and uses their hands. The referee sends them off: the substitute violated the field player’s contract, even though they could take the field. section 3.4.3
Listing 3.7 “Before”: Violating LSP
// The Parent Class
class Player
{
// The contract: any subclass MUST behave like a field player.
playFieldPosition() {
throw new Error("playFieldPosition() must be" +
"implemented by subclass.");
}
}
class Goalie extends Player
{
playFieldPosition() { console.log("Stays near the net, uses hands."); } #A
}
// The Application
class Coach
{
directFieldPlay(fieldPlayer) { fieldPlayer.playFieldPosition(); } #B
}
// The coach tries to substitute a Goalie into the midfield…
const coach = new Coach();
coach.directFieldPlay(new Goalie()); #CThe Goalie implements playFieldPosition(), but its goalie behavior does not fulfill the field-player contract expected by Coach. section 3.4.3
Listing 3.8 “After”: Following LSP
// The Parent Class (same as before)
class Player {
playFieldPosition() {
throw new Error(
"playFieldPosition() must be implemented by subclass.");
}
}
// Midfielder subclass
class Midfielder extends Player { #A
playFieldPosition() { #A
console.log("Controlling the midfield, tackling."); #A
} #A
} #A
// Forward subclass
class Forward extends Player { #A
playFieldPosition() { #A
console.log("Leading the attack and trying to score."); #A
} #A
} #A
// The Application (same as before)
class Coach {
directFieldPlay(fieldPlayer) { fieldPlayer.playFieldPosition(); }
}
// These substitutions work perfectly.
coach.directFieldPlay(new Midfielder()); // #B
coach.directFieldPlay(new Forward()); // #BMidfielder and Forward both fulfill the field-player contract, so Coach can use either without special checks. section 3.4.3
Reliable substitutions make shared contracts easier to trust and reduce coupling between modules. As a practical check, ask whether a caller can use each child as promised by the parent—not merely whether the call succeeds. section 3.4.3 section 3.11
The same concern appears when checkout logic depends on one payment library’s specific response object: swapping in another provider or a mock becomes difficult. A caller tied to concrete details cannot easily rely on an interchangeable service. section 10.4.1





