Polymorphism
medium 45 minOne call, many behaviours: the caller asks for the same thing, and the object that receives the call decides how it is done.
Video lesson · Chapter 1 of 6
Make a prediction
See it run
Follow one call: who may be asked, who is asked, and which version runs.
Operations
The type switch
Three functions ask the same question. A podcast arrives.
Step 1 of 5
Two kinds
Songs and radio. Three functions switch on the kind, and all agree.
Step 1: Two kinds
def minutes(item): if item.kind == "song": return item.seconds // 60 elif item.kind == "podcast": return item.seconds // 60 return 0- Good for
- One place, fixed kinds
- Costs
- Each kind edits every copy
- Places for a new kind
- 3
End a chain with an error, never with a quiet default.
In the real world
The same polymorphism doing real jobs. Pick one and step through it.
The same signal reaches three devices.
Step 1 of 4
A button
The remote sends one signal: power.
Step 1: A button
Common mistakes
The bugs interviewers watch for, with the fix beside each.
A subclass for a number
minorOnly the value differs, so no behaviour is overridden.
Wrongclass PremiumCustomer(Customer): def percent(self): return 20RightCustomer(name, percent=20)Overload instead of override
criticalCollections call equals(Object). The new method is never used.
Wrongpublic boolean equals(Point p) { ... }Right@Overridepublic boolean equals(Object o) { ... }Asking for the class after the call
majorThe contract lacks something, and the next kind is an edit here.
Wrongif isinstance(item, Podcast): at = item.positionRightif isinstance(item, Resumable): at = item.resume_at()A kind that cannot keep the contract
criticalEvery loop now needs a special case.
Wrongclass LiveRadio: def minutes(self): raise NotImplementedErrorRightdef minutes(self): return None # allowed by the contractWork in the parent's constructor
majorThe child's version runs before the child's fields exist.
Wrongdef __init__(self): self.text = self.render()Rightdef text(self): return self.render()
Interview tips
Two questions
- May I call it? Static type
- Which version? Dynamic type
- Which overload? Declared arguments
Contract first
- Write it from the caller's side
- Admit unknown in the type
- Split abilities off
What grows?
- Kinds: methods
- Operations: switch or visitor
- Values: a field
Review
- Override markers everywhere
- No quiet default
- One table for tags