Chain of responsibility
medium 45 minA request travels past several handlers until one takes it, or until one stops it.
Watch lesson4:36
Example: expense approval
The same idea without linked objects: a list of data.
The point: when handlers differ only in numbers, they are not classes. They are rows.
Problem
15,000 dollars for a conference
A manager approves up to 1,000, a director up to 10,000, the VP Finance up to 50,000, the CEO without limit. Nobody approves their own expense. Auditors want to see who looked at it and why it went on.
The way of one expense
Approval chain
1/3A list in order
The chain is a list. An approver does not know the next one.
has (lives on)depends onuses
Build the approval chain
What goes in and what comes out.
from dataclasses import dataclass@dataclass(frozen=True)class Expense: who: str amount: int # whole dollars reason: str@dataclass(frozen=True)class Decision: approved_by: str trail: tupleLines 4 to 8
Whole dollars. Money in floats would one day put 1,000 above 1,000.
1 of 2
Linked objects or a list?
| Linked handlers | List and runner | |
|---|---|---|
| Handler knows | the next one | nothing |
| Same handler in two chains | no, it has one next | yes |
| Trail, timing, limits | in the base class | in the loop |
| Work after the rest | natural | needs composed functions |
| Change while running | dangerous | swap the whole list |