AlgoViz

Chain of responsibility

medium 45 min

A 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

  1. Interviewer

    Support tickets have a priority. Level 1 handles low, level 2 medium, engineering high and critical. Design the routing.

  2. You

    Is the priority the only thing that decides? If yes, a map from priority to team is enough, and I would say so.

  3. 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.

  4. 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?

  5. Interviewer

    It must never be lost.

Python
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 None
The first version. It is not wrong. It is closed: the next team edits it, and the next region copies it.

Write down

Requirements

RequirementConsequence in the design
Exactly one team resolves a ticketDispatch flavour: stop at the first taker
Teams decide by their own rulecan_handle per class
Regions have different teams and ordersThe chain is built from outside
Critical tickets page someoneAn action of engineering, not of the chain
No ticket is lostA triage handler at the end, and an exception if it is missing
Left outAssignment 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
Unhandled with 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
Triage keeps 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.