call(back)

Inheritance or Composition?

Inheritance or composition — which do you reach for, and why?

Answer out loud in under a minute: a definition, one concrete example, and one pitfall or trade-off.

Hints

Hint 1

Say what each models ("is a" versus "has a") and what a change in a base class does to its children.

Solution

Show the approach

Answer

Inheritance models "is a" and ties the child to the parent's implementation, so a change in the base class ripples down. Composition models "has a" and combines small parts. Prefer composition when behaviors vary independently. In React, hooks and children are composition, which is why class hierarchies of components are rare.

How inheritance works in JavaScript, in code, is Inheritance Without class.

Asked at