06 / 12

Why is Composition often preferred over Inheritance? (Fragile Base Class problem)

Difficulty: 4/10

Composition Over Inheritance

Composition is often preferred because it reduces coupling and allows behavior to be changed by replacing collaborators rather than modifying an inheritance hierarchy. The Fragile Base Class problem occurs when a seemingly safe change to a base class unexpectedly changes the behavior of existing subclasses. Subclasses can also depend on implementation details of the parent, making evolution risky. Composition localizes behavior and makes dependencies explicit, which is particularly valuable in large systems.

javascript
  1. 1

    Composition reduces inheritance coupling.

  2. 2

    Dependencies become explicit through constructor injection or similar mechanisms.

  3. 3

    Components can be replaced without changing the owning class.

  4. 4

    Composition supports testing through mocks, fakes or alternative implementations.

  5. 5

    Inheritance remains appropriate when there is a stable and meaningful subtype relationship.

  6. 6

    The Fragile Base Class problem is a major reason to avoid deep inheritance hierarchies.

Follow-up Questions

  • Explain the Fragile Base Class problem with an example.
  • How does composition improve unit testing?
  • When is inheritance still preferable?
  • How does dependency injection support composition?
  • What is the difference between delegation and inheritance?
Share

Share via WhatsApp, X, Facebook, LinkedIn or copy link. Open Graph preview enabled.