Avoiding LSP Violations with Composition
You'll learn: How using composition instead of inheritance can prevent behavioral mismatches and preserve substitutability.
The Core Problem with Inheritance
When you force relationships through inheritance, you sometimes create situations where a subclass can't truly behave like its parent class—violating the Liskov Substitution Principle. The classic Rectangle-Square problem you just learned demonstrates this perfectly: a Square is-a Rectangle mathematically, but behaviorally, they're incompatible.
Composition to the Rescue
Instead of saying "Square is-a Rectangle" (inheritance), composition lets you say "Square has-a shape with equal sides." You build objects by combining smaller, focused components rather than inheriting all behaviors from a parent.
Think of it like building with LEGO blocks versus carving from stone. Inheritance is like carving—you start with a big block (parent class) and must keep everything unless you break it. Composition is like LEGO—you assemble exactly what you need from independent pieces.
How It Prevents LSP Violations
With composition:
- You choose which behaviors to include, rather than inheriting everything
- Each component maintains its own contract without forcing incompatible behaviors
- Objects expose only what they actually support
- No need for awkward workarounds or throwing exceptions for inherited methods that don't fit
For example, instead of Square extends Rectangle, you might have both Square and Rectangle use a Dimensions component. Each manages its dimensions according to its own rules, without pretending to be substitutable when they're not.
The Trade-off
Composition requires more explicit wiring—you write more code to connect components. But this explicitness is actually beneficial: it makes relationships clear and prevents hidden behavioral assumptions.
Key Takeaway: Composition prevents LSP violations by letting you build objects from independent, focused components rather than forcing inheritance relationships that create behavioral incompatibilities.