CSE Roadmap

Core tier · about 3 hours · 7 parts

Part 6 of 7 · 2 min read

A decision guide

When to extend, and when to hold.

A decision guide

A short guide, from EJ and GoF (with one habit that is common practice):

  • Use inheritance when the subclass really is a kind of the parent, both live in the same package or team, and the parent is designed for extension. Interface inheritance has none of these problems.
  • Use composition to add behaviour to a class that is not designed for extension, to change behaviour at run time, or when the "is-a" test is only partly true.
  • Test the sentence. Say "a B is an A" aloud. If it is only "a B uses an A" or "a B has an A", use composition. (Common practice.)
  • Ask what happens if the parent changes. If the answer is "the subclass may break", prefer a wrapper.

Common mistake

Extending a class only to reuse a few of its methods. A Stack that extends Vector exposes every Vector method, including ones that break the stack rules.

Interview angle

Answer in your head first, then open it.

Why favour composition over inheritance?

Inheritance ties a subclass to its parent's implementation. Composition uses only the interface and can be swapped at run time.

Give an example where inheritance fails.

A set subclass counting insertions double-counts because the parent's addAll calls add.

When is inheritance fine?

Within one team and package, or for classes designed and documented for extension, and always for interface inheritance.

Check yourself: 1. Which kind of inheritance has none of the fragility problems? 2. How does the "is-a" sentence test help? 3. What is wrong with a Stack that extends Vector?

Words you will meet

Word Meaning
White-box reuse Reuse by subclassing, where the parent's inside is visible
Black-box reuse Reuse by holding objects and calling their interface
Composition Building behaviour by holding other objects
Forwarding Passing a call to a held object
Wrapper A class that holds another and adds behaviour
Delegation Handing a request to another object
Fragile base class A parent whose changes break its subclasses