Inheritance vs composition
medium 40 minTwo ways to reuse code.
Video lesson · Chapter 1 of 6
Make a prediction
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
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
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
criticalAll public methods of the parent come along, also the wrong ones.
Wrongclass Stack(list): ...Rightclass Stack: def __init__(self): self._items = []A method that throws
criticalThe child has a type whose promise it cannot keep.
Wrongclass Penguin(Bird): def fly(self): raise NotImplementedErrorRightclass Penguin: def swim(self): ...Override without knowing self calls
majorCalls inside the parent land in your method, or stop landing there.
Wrongclass Counted(Inbox): def add(self, x): ...Rightclass Counted: def __init__(self, inner): ...One class per combination
majorTwo axes multiply.
Wrongclass PdfMailReport(MailReport): ...RightReport(Pdf(), mail.send)Part made inside
minorIt cannot be replaced, not even in a test.
Wrongself._fly = Wings()Rightdef __init__(self, fly): self._fly = flyComposition as a religion
minorA small closed set of variants is clearer as a hierarchy.
WrongShape(kind_part, area_part, name_part)Rightclass 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