Codacoda
Back to Academy

coding principles

Composition Over Inheritance

Composition over inheritance is the principle that classes should achieve polymorphic behavior and code reuse by containing instances of other classes that implement the desired functionality, rather than inheriting from a base class. Inheritance creates rigid hierarchies and tight coupling — a change to a parent class ripples through all descendants. Composition allows mixing and matching behaviors at runtime, avoids the fragile base class problem, and keeps each component focused and independently testable.

Use Cases

  • Building game entities with mix-and-match capabilities (fly, swim, attack) instead of deep class hierarchies
  • Creating UI components by composing smaller components rather than extending base component classes
  • Implementing the Strategy pattern where behavior is injected via composition
  • Combining logging, retry, and caching behaviors as composable wrappers around a core service

Visualization

BEFOREAnimalmove()FlyingAnimalfly()SwimmingAnimalswim()Duckfly()?swim()?
Speed:1x
Duck needs to both fly and swim. With single inheritance, it can only extend one parent — FlyingAnimal OR SwimmingAnimal.Step 1 / 7

Implementation

Output

Click "Run Code" to see output...