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

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 hearThinkFirst move
"If they cannot solve it, it goes to"DispatchAsk what happens at the end
"Before we accept it we check"FilterAsk which checks have effects
"For every request we also want to log, measure, authenticate"Wrapping pipelineFix the order aloud
"Up to 1,000 the manager, above that"Dispatch with dataRows, not subclasses
"Customers have different rules"Several lists of the same linksBuild from configuration
"Depending on the type"Probably a mapSay 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

  1. Interviewer

    Every request should be rate limited, logged and authenticated.

  2. You

    That is a wrapping pipeline. Order first: catch errors outermost, then rate limit, because login is expensive, then redact and log, then authenticate.

  3. Interviewer

    Why log before authenticating?

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