Architecture

Choose Composition Over Inheritance for Flexible Behavior

Build behavior from focused collaborators when inheritance would create rigid hierarchies or fragile base classes.

Inheritance can express a genuine “is-a” relationship, but it also couples subclasses to base-class behavior and protected implementation details. Composition often provides more flexibility.

Recognize inheritance pressure

Deep hierarchies, overridden methods with surprising side effects, and subclasses that cannot honor base-class expectations are warning signs. A base class should define a stable contract, not expose every internal detail to descendants.

Compose capabilities

An object can delegate notification, pricing, storage, or formatting behavior to collaborators. Different implementations can be combined without creating a subclass for every feature combination.

Keep composition understandable

Too many tiny collaborators can make behavior hard to follow. Group cohesive operations and make dependencies visible. Composition is not automatically better if it simply distributes one simple algorithm across many files.

Use inheritance deliberately

Inheritance remains appropriate for stable substitutability and framework extension points with clear contracts. Prefer shallow hierarchies and test behavioral compatibility.

Checklist

  • Check whether subclasses truly satisfy the base contract.
  • Prefer focused collaborators for variable behavior.
  • Keep dependency wiring understandable.
  • Avoid deep and fragile hierarchies.
  • Use inheritance where substitutability is real.
Share this page Help other developers discover this resource.