Interface segregation (ISP)
medium 50 minNo client should be forced to depend on methods it does not use.
Video lesson · Chapter 1 of 6
Make a prediction
See it run
Who sees which methods, who must lie, and how far a change travels.
Operations
A printer that must scan
The interface says that every device can do six things. This one can do one.
Step 1 of 5
Six methods promised
Both clients accept any MultiFunctionDevice.
Step 1: Six methods promised
class SimplePrinter(MultiFunctionDevice): def print(self, doc): ... def scan(self): raise NotImplementedErrordef archive(device: MultiFunctionDevice): return device.scan()def archive_fixed(device: Scannable): return device.scan()- Use it to
- Show a lying type
- Watch out for
- Five stubs
- Error found
- run time
Ask where the error is found: by the checker, or by the customer.
In the real world
The same interface segregation doing real jobs. Pick one and step through it.
One remote with forty buttons, or one per need.
Step 1 of 4
Forty buttons
Asha needs two of them.
Step 1: Forty buttons
Common mistakes
The bugs interviewers watch for, with the fix beside each.
A copy of the class as interface
majorAll callers are as coupled as before. There is only one file more.
Wrongclass IOrderStore(ABC): # all 31 methodsRightclass DayReader(Protocol): def list_day(self, day): ...Throwing in a stub
criticalThe type says yes, the object says no, and the customer finds out.
Wrongclass Robot(Worker): def eat(self): raise NotImplementedErrorRightclass Robot(Workable, Reportable): ...Casting back
criticalThe narrow type is a lie if the caller reaches behind it.
Wrongdef report(orders: DayReader): cast(OrderStore, orders).purge("...")Rightdef clean(orders: Retention, before): orders.purge(before)Tearing a pair
majorTwo roles may come from two objects. Then the lock that was taken is not the one released.
Wrongdef use(a: Lockable, b: Unlockable): ...Rightdef use(lock: Lock): with lock: ...A wrapper that forgets
majorOptional abilities of the inner object vanish without an error.
Wrongclass Count: def write(self, t): ... # flush is goneRightdef counting(inner): return KeepsFlush(inner) if isinstance(inner, Flushable) else LosesFlush(inner)
Interview tips
Start at the callers
- Rows: clients
- Columns: methods
- Same callers, same role
Name the need
- Printable, Refunds
- Not IOrderStore2
- No name, wrong group
Know when to stop
- Used together
- Tied by a rule
- One method: a function
Think of outsiders
- New abstract method breaks
- Default if computable
- Second role if optional