AlgoViz

Inheritance vs composition

medium 40 min

Two ways to reuse code.

Video lesson · Chapter 1 of 6

Make a prediction

0:00 / 4:52

See it run

Follow one call: does it land in a parent, in a child, or in a part?

Operations

The penguin crash

A base class promises too much.

Step 1 of 4

Bird can fly

air showwants BirdresultnothingeagleEagle is a Birdfly()inherited

It looks reasonable. An eagle gets fly for free.

Step 1: Bird can fly

class Bird:    def fly(self): return "flying"class Penguin(Bird):    def fly(self): raise NotImplementedErrorfor b in birds:    b.fly()
Good for
Never
Costs
A caller that breaks

Is-a in biology is not is-a in behaviour.

In the real world

The same inheritance vs composition doing real jobs. Pick one and step through it.

Fixed shape or free combination.

Step 1 of 4

Dolls

is abig dollparentshaperoundsmall dollchildshaperoundnotefits

The small doll has the shape of the big one.

Step 1: Dolls

Common mistakes

The bugs interviewers watch for, with the fix beside each.

  • Inherit to save typing

    critical

    All public methods of the parent come along, also the wrong ones.

    Wrong
    class Stack(list): ...
    Right
    class Stack:    def __init__(self): self._items = []
  • A method that throws

    critical

    The child has a type whose promise it cannot keep.

    Wrong
    class Penguin(Bird):    def fly(self): raise NotImplementedError
    Right
    class Penguin:    def swim(self): ...
  • Override without knowing self calls

    major

    Calls inside the parent land in your method, or stop landing there.

    Wrong
    class Counted(Inbox):    def add(self, x): ...
    Right
    class Counted:    def __init__(self, inner): ...
  • One class per combination

    major

    Two axes multiply.

    Wrong
    class PdfMailReport(MailReport): ...
    Right
    Report(Pdf(), mail.send)
  • Part made inside

    minor

    It cannot be replaced, not even in a test.

    Wrong
    self._fly = Wings()
    Right
    def __init__(self, fly): self._fly = fly
  • Composition as a religion

    minor

    A small closed set of variants is clearer as a hierarchy.

    Wrong
    Shape(kind_part, area_part, name_part)
    Right
    class Circle(Shape): ...   # sealed, one level

Interview tips

  • Ask three questions

    • Used as that type?
    • Every promise kept?
    • Parent made for it?
  • Count axes

    • Adjectives in names
    • One axis: maybe a tree
    • More: parts
  • Wrap well

    • Narrow the interface first
    • Forward, then add
    • Hand out the outer object only
  • Inherit well

    • Final by default
    • Few hooks with a contract
    • Two levels