AlgoViz

Chain of responsibility

medium 45 min

A request travels past several handlers until one takes it, or until one stops it.

Video lesson · Chapter 1 of 6

Make a prediction

0:00 / 4:36

See it run

Requests on their way: who is asked, who takes it, who never sees it.

Operations

A critical ticket

The server is down. The ticket enters at level 1, like every ticket.

Step 1 of 8

Before

firstnextnextnextapiTicketApiticketnonelevel1Level1takesLOWlevel2Level2takesMEDIUMengineeringEngineeringtakesHIGH uppagednonetriageTriagetakesallinbox0

Level1, Level2, Engineering, Triage

The ticket interface holds one reference: the first handler. The links are set.

Step 1: Before

class SupportHandler:    def handle(self, ticket):        if self.can_handle(ticket):            return self.resolve(ticket)        if self._next is None:            raise Unhandled(ticket)        return self._next.handle(ticket)class Level1(SupportHandler):    def can_handle(self, ticket):        return ticket.priority == LOWclass Engineering(SupportHandler):    def can_handle(self, ticket):        return ticket.priority >= HIGH    def resolve(self, ticket):        if ticket.priority == CRITICAL:            self._pager.append(ticket.id)        return "Engineering resolved"
Watch
Who says no
Result
3 handlers asked

The client makes one call. Count the calls that follow.

In the real world

The same chain of responsibility doing real jobs. Pick one and step through it.

A fluent chain kept in the wrong variable.

Step 1 of 3

It reads well

firstnextnextchainvariableuserUserCheckstockStockCheckfraudFraudCheck

What we believe

user().set_next(stock()).set_next(fraud()). Three checks, one line.

Step 1: It reads well

Common mistakes

The bugs interviewers watch for, with the fix beside each.

  • Forgetting return

    critical

    The ticket is resolved, but the caller gets None.

    Wrong
    def handle(self, t):    if self.can(t): return self.resolve(t)    self._next.handle(t)
    Right
    def handle(self, t):    if self.can(t): return self.resolve(t)    return self._next.handle(t)
  • Silence at the end

    critical

    A lost request looks like a success.

    Wrong
    if self._next:    return self._next.handle(t)
    Right
    if self._next is None:    raise Unhandled(t)return self._next.handle(t)
  • Keeping the wrong end

    critical

    set_next returns the last handler.

    Wrong
    chain = a.set_next(b).set_next(c)
    Right
    a.set_next(b).set_next(c)chain = a
  • Request data in a handler

    critical

    Two requests at once overwrite each other.

    Wrong
    class Auth:    def handle(self, r):        self.user = find(r.token)
    Right
    class Auth:    def handle(self, r):        r.user = find(r.token)
  • Wide before narrow

    major

    The general handler takes everything.

    Wrong
    link(AnyTicket(), Critical())
    Right
    link(Critical(), AnyTicket())
  • Swallowing errors of a check

    critical

    A check that crashes lets everyone in.

    Wrong
    try: check(r)except Exception: pass
    Right
    try: check(r)except Exception: return Refused("check broken")

Interview tips

  • Name the flavour

    • One takes it.
    • Each may refuse.
    • Each wraps the rest.
  • Decide the end

    • Catch-all with a counter.
    • Exception behind it.
    • Or accepted.
  • Own the order

    • One place.
    • Checked at start.
    • Printed in the log.
  • Keep links small

    • One rule.
    • No data per request.
    • No knowledge of neighbours.
  • Know when not

    • One key: a map.
    • All must run: a loop.
    • Three ifs: three ifs.