Preventing subclassing
medium 45 minA subclass can replace your methods, and then your promises are only as good as theirs.
Video lesson · Chapter 1 of 6
Make a prediction
See it run
Which method runs, who can replace it, and where a child is refused.
Operations
The broken promise
RentService trusts Account. A child removes the check.
Step 1 of 5
The promise
An Account never goes below zero. RentService relies on it.
Step 1: The promise
class FreeWithdrawAccount(BankAccount): def withdraw(self, cents): self.cents -= cents # no check return Truedef pay_rent(account): account.withdraw(90_000) assert account.cents >= 0- Shows
- Why to lock at all
- Remember
- One child is enough
The caller cannot see which child it got. That is the point of a type.
In the real world
The same preventing subclassing doing real jobs. Pick one and step through it.
Who may extend, and what may be replaced.
Step 1 of 5
Final method
| children | overrides | example | |
|---|---|---|---|
| Final method | yes | not that one | Account |
Children are welcome. One step is locked.
Step 1: Final method
Common mistakes
The bugs interviewers watch for, with the fix beside each.
A rule that children may replace
criticalThe invariant is only as good as the worst child.
Wrongdef withdraw(self, cents): ... # anybody may overrideRight@finaldef withdraw(self, cents): ... self._on_withdraw(cents)Believing @final
majorPython does not check it when the program runs.
Wrong@finalclass Token: ...Right@finalclass Token: def __init_subclass__(cls, **kw): raise TypeError("Token is final")Extending to count
majorThe parent may call its own methods, and the child counts twice.
Wrongclass CountingList(list): ...Rightclass CountingList: def __init__(self, inner): self._inner = innerA default in a closed switch
majorIt hides the next kind that is added.
Wrongcase _: return "pending"Rightcase _: assert_never(result)Final for everything
minorEntities and proxied services need children made by the framework.
Wrong# Javafinal class OrderEntity { ... }Right# Javaclass OrderEntity { ... } // the ORM subclasses it
Interview tips
Start with the promise
- Name it
- Who relies on it?
- Who could break it?
Smallest lock
- Method
- List
- Class
Leave a way
- Hook after the change
- Interface and wrapper
- Listener
Know the limits
- Not immutability
- Not speed
- Not a wall against attackers