Chain of responsibility
medium 45 minA request travels past several handlers until one takes it, or until one stops it.
Video lesson · Chapter 1 of 6
Make a prediction
See it run
Requests on their way: who is asked, who takes it, who never sees it.
Operations
A critical ticket
The server is down. The ticket enters at level 1, like every ticket.
Step 1 of 8
Before
Level1, Level2, Engineering, Triage
The ticket interface holds one reference: the first handler. The links are set.
Step 1: Before
class SupportHandler: def handle(self, ticket): if self.can_handle(ticket): return self.resolve(ticket) if self._next is None: raise Unhandled(ticket) return self._next.handle(ticket)class Level1(SupportHandler): def can_handle(self, ticket): return ticket.priority == LOWclass Engineering(SupportHandler): def can_handle(self, ticket): return ticket.priority >= HIGH def resolve(self, ticket): if ticket.priority == CRITICAL: self._pager.append(ticket.id) return "Engineering resolved"- Watch
- Who says no
- Result
- 3 handlers asked
The client makes one call. Count the calls that follow.
In the real world
The same chain of responsibility doing real jobs. Pick one and step through it.
A fluent chain kept in the wrong variable.
Step 1 of 3
It reads well
What we believe
user().set_next(stock()).set_next(fraud()). Three checks, one line.
Step 1: It reads well
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Forgetting return
criticalThe ticket is resolved, but the caller gets None.
Wrongdef handle(self, t): if self.can(t): return self.resolve(t) self._next.handle(t)Rightdef handle(self, t): if self.can(t): return self.resolve(t) return self._next.handle(t)Silence at the end
criticalA lost request looks like a success.
Wrongif self._next: return self._next.handle(t)Rightif self._next is None: raise Unhandled(t)return self._next.handle(t)Keeping the wrong end
criticalset_next returns the last handler.
Wrongchain = a.set_next(b).set_next(c)Righta.set_next(b).set_next(c)chain = aRequest data in a handler
criticalTwo requests at once overwrite each other.
Wrongclass Auth: def handle(self, r): self.user = find(r.token)Rightclass Auth: def handle(self, r): r.user = find(r.token)Wide before narrow
majorThe general handler takes everything.
Wronglink(AnyTicket(), Critical())Rightlink(Critical(), AnyTicket())Swallowing errors of a check
criticalA check that crashes lets everyone in.
Wrongtry: check(r)except Exception: passRighttry: check(r)except Exception: return Refused("check broken")
Interview tips
Name the flavour
- One takes it.
- Each may refuse.
- Each wraps the rest.
Decide the end
- Catch-all with a counter.
- Exception behind it.
- Or accepted.
Own the order
- One place.
- Checked at start.
- Printed in the log.
Keep links small
- One rule.
- No data per request.
- No knowledge of neighbours.
Know when not
- One key: a map.
- All must run: a loop.
- Three ifs: three ifs.