Chain of responsibility
medium 45 minA request travels past several handlers until one takes it, or until one stops it.
Watch lesson4:36
When it comes up
The moments this idea belongs in a design interview, and the moments it does not.
Listen
Words that announce it
| You hear | Think | First move |
|---|---|---|
| "If they cannot solve it, it goes to" | Dispatch | Ask what happens at the end |
| "Before we accept it we check" | Filter | Ask which checks have effects |
| "For every request we also want to log, measure, authenticate" | Wrapping pipeline | Fix the order aloud |
| "Up to 1,000 the manager, above that" | Dispatch with data | Rows, not subclasses |
| "Customers have different rules" | Several lists of the same links | Build from configuration |
| "Depending on the type" | Probably a map | Say so |
Design the checks before an order is accepted. What do you draw?
BreaksOne method with all checks
- How
- Five ifs in OrderService.
- Limit
- Gift orders copy it, and one copy misses the fraud check.
- Choose when
- A first sketch, for one path only.
WorksLinked check objects
- How
- Base class with next, one class per check.
- Limit
- One object per chain, relinking at run time is unsafe.
- Choose when
- One fixed chain.
StrongIndependent checks in immutable lists
- How
- A runner stops at the first refusal, records a trail, knows per check what failure means.
- Limit
- A little more code in the runner.
- Choose when
- Several paths, changes, remote calls.
Two minutes that show it
Interviewer
Every request should be rate limited, logged and authenticated.
You
That is a wrapping pipeline. Order first: catch errors outermost, then rate limit, because login is expensive, then redact and log, then authenticate.
Interviewer
Why log before authenticating?
You
So that refused requests appear in the log. The price is that the log line has no user yet. I write it on the way out, when the user is known.