Repaso
Español
Design & PracticesIntermediateDP-14

'Favor composition over inheritance' mainly helps avoid…

Options

  1. Using classes at all in the design of a program
  2. Fragile deep hierarchies, where base changes ripple (Correct option)
  3. Writing interfaces for every class of the program
  4. Using polymorphism in the design of a program

Answer

Fragile, deep hierarchies where changes in a base class ripple into subclasses

Why

Inheritance ('is-a') ties a child tightly to its parent: a change in the parent can break every child, and deep hierarchies get hard to understand.

Composition ('has-a') builds an object from smaller parts it holds as attributes: a Car HAS an Engine. Parts can be swapped easily, even at runtime.

Use inheritance only for true 'is-a' relationships and keep it shallow.

Remember

Prefer 'has-a' (composition) to 'is-a' (inheritance).

Key terms

Practice this question in Repaso