Chain of responsibility
medium 45 minA request travels past several handlers until one takes it, or until one stops it.
Watch lesson4:36
Verify
Trace, boundaries, and tests that find real bugs.
The point: test each handler alone, then the order, then the end.
Trace
Ticket 4 by hand
| Step | Object | canHandle | Stack |
|---|---|---|---|
| 1 | Level1 | CRITICAL is LOW? no | Level1 |
| 2 | Level2 | CRITICAL is MEDIUM? no | Level1, Level2 |
| 3 | Engineering | CRITICAL is HIGH or more? yes | Level1, Level2, Engineering |
| 4 | Engineering | pager gets 4, text returned | Level1, Level2 |
| 5 | Level2, Level1 | return what they got | empty |
Tests
Three kinds
Python
class Handler: def __init__(self): self.next = None def handle(self, n): if self.can(n): return self.name if self.next is None: raise LookupError(n) return self.next.handle(n)class Low(Handler): name = "low" def can(self, n): return n < 10class High(Handler): name = "high" def can(self, n): return 10 <= n < 100class Spy(Handler): name = "spy" def __init__(self): super().__init__(); self.seen = [] def can(self, n): self.seen.append(n); return Truedef link(*hs): for a, b in zip(hs, hs[1:]): a.next = b return hs[0]# 1. alone: the boundary of one ruleassert Low().can(9) and not Low().can(10)# 2. passing on: the spy sees exactly what Low did not takespy = Spy()chain = link(Low(), spy)assert chain.handle(5) == "low" and spy.seen == []assert chain.handle(50) == "spy" and spy.seen == [50]# 3. the endtry: link(Low(), High()).handle(1000) raise AssertionError("lost")except LookupError as e: print("end reached with", e)# 4. order does not matter, because the rules exclude each otherfor n in (0, 9, 10, 99): assert link(Low(), High()).handle(n) == link(High(), Low()).handle(n)print("all ok")Java
@Testvoid level1PassesACriticalTicketOn() { List<Ticket> seen = new ArrayList<>(); SupportHandler recorder = new SupportHandler() { protected boolean canHandle(Ticket t) { return true; } protected String resolve(Ticket t) { seen.add(t); return "recorded"; } }; Ticket crash = new Ticket(1, "Crash", Priority.CRITICAL); String answer = Chain.link(new Level1(), recorder).handle(crash); assertEquals("recorded", answer); // the answer came back assertEquals(List.of(crash), seen); // and the request arrived}verify(h2): Mockito can only verify calls on a mock or a spy, and a real Level2 is neither.What each test catches
| Bug | Found by |
|---|---|
Forgot return before next.handle | asserting the answer, not only the call |
| Off by one at a limit | the boundary test of one handler |
| Two rules overlap | the order test: swapping changes the result |
| A gap between rules | every value of the enum through the real chain |
| Chain starts at the wrong handler | sending a request the first one must refuse |