principleModeratepending
Prefer composition over inheritance -- flexible code reuse
Viewed 0 times
compositioninheritancemixininterfacecouplinghas-ais-a
Problem
Deep inheritance hierarchies create fragile coupling. Changing a base class breaks all subclasses. Diamond inheritance, method resolution order, and override confusion make code hard to understand.
Solution
Compose behavior by combining small, focused objects/functions instead of inheriting from a chain of base classes. Use interfaces/protocols to define contracts. Inject collaborators instead of inheriting from them. Mixins and higher-order functions provide reuse without hierarchy. Inheritance is fine for true is-a relationships (1-2 levels deep), but composition handles has-a and can-do relationships better.
Why
Inheritance is the tightest form of coupling. A subclass depends on the entire implementation of its parent. Composition depends only on the interface.
Revisions (0)
No revisions yet.