MEPX
Chapter 5 of 10All chapters

Chapter 5 of 10

Composition over inheritance

Has-a is usually safer than is-a.

The alternative

Instead of inheriting behaviour, hold an object that provides it. A Car with an Engine can change engines; a Car extending Engine cannot.

  • Composition can be changed at runtime and combined freely.
  • Reach for inheritance only when the is-a relationship is genuinely permanent.

Dependency injection

Passing collaborators in rather than creating them inside makes an object testable, because a test can pass a simple stand-in. That is most of what the term means.