Chain of responsibility
medium 45 minA request travels past several handlers until one takes it, or until one stops it.
Watch lesson4:36
Problem
A support desk: what is asked, what hurts, and the first decisions.
The point: the desk is easy to code with three ifs. The task is to make the list of desks something that can be changed, reused and checked.
The task
What we are asked
The first minute
Interviewer
Support tickets have a priority. Level 1 handles low, level 2 medium, engineering high and critical. Design the routing.
You
Is the priority the only thing that decides? If yes, a map from priority to team is enough, and I would say so.
Interviewer
Today yes. Next quarter some teams will look at the customer's contract and the time of day, and regions will have different desks.
You
Then each team should decide for itself, and each region needs its own list of teams. That is a chain. One question: what should happen to a ticket that nobody takes?
Interviewer
It must never be lost.
def route(ticket): if ticket.priority == "low": return level1(ticket) elif ticket.priority == "medium": return level2(ticket) elif ticket.priority in ("high", "critical"): return engineering(ticket) # no else: an unknown priority returns NoneWrite down
Requirements
| Requirement | Consequence in the design |
|---|---|
| Exactly one team resolves a ticket | Dispatch flavour: stop at the first taker |
| Teams decide by their own rule | can_handle per class |
| Regions have different teams and orders | The chain is built from outside |
| Critical tickets page someone | An action of engineering, not of the chain |
| No ticket is lost | A triage handler at the end, and an exception if it is missing |
| Left out | Assignment to a person, reopening, time limits |
A ticket reaches the end and nobody took it. What now?
BreaksReturn nothing
- How
- The base handler returns None when there is no next.
- Limit
- The caller cannot tell resolved from lost. It is found weeks later.
- Choose when
- Never for work that must be done.
WorksRaise an exception
- How
Unhandledwith the ticket in it.- Limit
- The customer sees an error. Someone must catch it and keep the ticket.
- Choose when
- When it is a programming error: the chain should cover everything.
StrongA last handler, and an exception behind it
- How
Triagekeeps the ticket in an inbox and counts it. The exception only fires if someone built a chain without triage.- Limit
- Triage hides gaps unless somebody watches its count.
- Choose when
- Work that must not be lost.