# Chain of Responsibility: The Coin Sorter

When every voice command has to pass a night-time check, a someone's-home check and a permission check, one function full of ifs grows with every new check and gets copied for every new device; a Chain of Responsibility makes each check its own link that stops the command or passes it on, so checks can be added, reordered and reused.

Journeyman · OOP · Updated November 17, 2026

By Gregor Dzierzon

## After this lesson you can

- Pass a request along a chain of checks, each of which stops it or passes it on
- Spot the smells that point to Chain of Responsibility: one method with a growing, ordered list of checks

## Key takeaways

- The smell: one method with a growing, ordered list of checks, copied with small changes wherever a slightly different set is needed.
- The cause: the checks, their order and the real work are welded into one function.
- The fix: each check is its own link. It stops the request with a reason or passes it to the next link; the last link does the work.
- The modern version is a list of small check functions and a loop that stops at the first one that says no.
- Skip it when there are one or two checks that never change, or when every check must run and report, not stop.

**Before this:** *Meet the Smart-Home Hub*, interfaces (a promise any class can keep), and passing a function as a value.

Maya can talk to the hub: "unlock the front door", "play the news", "lights on". Before the hub does anything, a voice command has to pass three checks, in order. **Is it night?** After 22:00 the speakers stay quiet. **Is someone home?** If nobody is, the voice probably came from the TV. **Is this person allowed?** A guest can't unlock doors. Now Sam wants a fourth check for when the family is away, and the new wall panel needs only one of the three. By the end of this lesson you'll have met the pattern for this, called *Chain of Responsibility*.

## The symptom: one function full of checks, and a copy of it

Here's the voice handler, and the wall panel's handler, which copied the one check it needs:

```csharp
Console.WriteLine(HandleVoice(new VoiceCommand("Maya", "unlock the front door", 21, true)));
Console.WriteLine(HandleVoice(new VoiceCommand("guest", "unlock the front door", 21, true)));
Console.WriteLine(HandleVoice(new VoiceCommand("Sam", "play the news", 23, true)));
Console.WriteLine(HandleVoice(new VoiceCommand("Maya", "lights on", 8, false)));
Console.WriteLine(HandlePanel(new VoiceCommand("guest", "unlock the front door", 21, true)));

string HandleVoice(VoiceCommand command)
{
    if (command.Hour >= 22 && command.Words.StartsWith("play"))
    {
        return "Stopped: it's after 22:00, so the speakers stay quiet";
    }
    if (!command.SomeoneHome)
    {
        return "Stopped: nobody's home (was that the TV?)";
    }
    if (command.Who == "guest" && command.Words.Contains("unlock"))
    {
        return "Stopped: a guest can't unlock doors";
    }
    return $"Done: {command.Words}";
}

// The wall panel needs only the permission check, so it has its own copy.
string HandlePanel(VoiceCommand command)
{
    if (command.Who == "guest" && command.Words.Contains("unlock"))
    {
        return "Stopped: a guest can't unlock doors";
    }
    return $"Done: {command.Words}";
}

record VoiceCommand(string Who, string Words, int Hour, bool SomeoneHome);
```

```text
Done: unlock the front door
Stopped: a guest can't unlock doors
Stopped: it's after 22:00, so the speakers stay quiet
Stopped: nobody's home (was that the TV?)
Stopped: a guest can't unlock doors
```

```java
record VoiceCommand(String who, String words, int hour, boolean someoneHome) {}

String handleVoice(VoiceCommand command) {
    if (command.hour() >= 22 && command.words().startsWith("play")) {
        return "Stopped: it's after 22:00, so the speakers stay quiet";
    }
    if (!command.someoneHome()) {
        return "Stopped: nobody's home (was that the TV?)";
    }
    if (command.who().equals("guest") && command.words().contains("unlock")) {
        return "Stopped: a guest can't unlock doors";
    }
    return "Done: " + command.words();
}

// The wall panel needs only the permission check, so it has its own copy.
String handlePanel(VoiceCommand command) {
    if (command.who().equals("guest") && command.words().contains("unlock")) {
        return "Stopped: a guest can't unlock doors";
    }
    return "Done: " + command.words();
}

void main() {
    IO.println(handleVoice(new VoiceCommand("Maya", "unlock the front door", 21, true)));
    IO.println(handleVoice(new VoiceCommand("guest", "unlock the front door", 21, true)));
    IO.println(handleVoice(new VoiceCommand("Sam", "play the news", 23, true)));
    IO.println(handleVoice(new VoiceCommand("Maya", "lights on", 8, false)));
    IO.println(handlePanel(new VoiceCommand("guest", "unlock the front door", 21, true)));
}
```

```text
Done: unlock the front door
Stopped: a guest can't unlock doors
Stopped: it's after 22:00, so the speakers stay quiet
Stopped: nobody's home (was that the TV?)
Stopped: a guest can't unlock doors
```

```python
class VoiceCommand:
    def __init__(self, who, words, hour, someone_home):
        self.who = who
        self.words = words
        self.hour = hour
        self.someone_home = someone_home


def handle_voice(command):
    if command.hour >= 22 and command.words.startswith("play"):
        return "Stopped: it's after 22:00, so the speakers stay quiet"
    if not command.someone_home:
        return "Stopped: nobody's home (was that the TV?)"
    if command.who == "guest" and "unlock" in command.words:
        return "Stopped: a guest can't unlock doors"
    return f"Done: {command.words}"


# The wall panel needs only the permission check, so it has its own copy.
def handle_panel(command):
    if command.who == "guest" and "unlock" in command.words:
        return "Stopped: a guest can't unlock doors"
    return f"Done: {command.words}"


print(handle_voice(VoiceCommand("Maya", "unlock the front door", 21, True)))
print(handle_voice(VoiceCommand("guest", "unlock the front door", 21, True)))
print(handle_voice(VoiceCommand("Sam", "play the news", 23, True)))
print(handle_voice(VoiceCommand("Maya", "lights on", 8, False)))
print(handle_panel(VoiceCommand("guest", "unlock the front door", 21, True)))
```

```text
Done: unlock the front door
Stopped: a guest can't unlock doors
Stopped: it's after 22:00, so the speakers stay quiet
Stopped: nobody's home (was that the TV?)
Stopped: a guest can't unlock doors
```

```javascript
class VoiceCommand {
  constructor(who, words, hour, someoneHome) {
    this.who = who;
    this.words = words;
    this.hour = hour;
    this.someoneHome = someoneHome;
  }
}

function handleVoice(command) {
  if (command.hour >= 22 && command.words.startsWith("play")) {
    return "Stopped: it's after 22:00, so the speakers stay quiet";
  }
  if (!command.someoneHome) {
    return "Stopped: nobody's home (was that the TV?)";
  }
  if (command.who === "guest" && command.words.includes("unlock")) {
    return "Stopped: a guest can't unlock doors";
  }
  return `Done: ${command.words}`;
}

// The wall panel needs only the permission check, so it has its own copy.
function handlePanel(command) {
  if (command.who === "guest" && command.words.includes("unlock")) {
    return "Stopped: a guest can't unlock doors";
  }
  return `Done: ${command.words}`;
}

console.log(handleVoice(new VoiceCommand("Maya", "unlock the front door", 21, true)));
console.log(handleVoice(new VoiceCommand("guest", "unlock the front door", 21, true)));
console.log(handleVoice(new VoiceCommand("Sam", "play the news", 23, true)));
console.log(handleVoice(new VoiceCommand("Maya", "lights on", 8, false)));
console.log(handlePanel(new VoiceCommand("guest", "unlock the front door", 21, true)));
```

```text
Done: unlock the front door
Stopped: a guest can't unlock doors
Stopped: it's after 22:00, so the speakers stay quiet
Stopped: nobody's home (was that the TV?)
Stopped: a guest can't unlock doors
```

```typescript
class VoiceCommand {
  who: string;
  words: string;
  hour: number;
  someoneHome: boolean;
  constructor(who: string, words: string, hour: number, someoneHome: boolean) {
    this.who = who;
    this.words = words;
    this.hour = hour;
    this.someoneHome = someoneHome;
  }
}

function handleVoice(command: VoiceCommand): string {
  if (command.hour >= 22 && command.words.startsWith("play")) {
    return "Stopped: it's after 22:00, so the speakers stay quiet";
  }
  if (!command.someoneHome) {
    return "Stopped: nobody's home (was that the TV?)";
  }
  if (command.who === "guest" && command.words.includes("unlock")) {
    return "Stopped: a guest can't unlock doors";
  }
  return `Done: ${command.words}`;
}

// The wall panel needs only the permission check, so it has its own copy.
function handlePanel(command: VoiceCommand): string {
  if (command.who === "guest" && command.words.includes("unlock")) {
    return "Stopped: a guest can't unlock doors";
  }
  return `Done: ${command.words}`;
}

console.log(handleVoice(new VoiceCommand("Maya", "unlock the front door", 21, true)));
console.log(handleVoice(new VoiceCommand("guest", "unlock the front door", 21, true)));
console.log(handleVoice(new VoiceCommand("Sam", "play the news", 23, true)));
console.log(handleVoice(new VoiceCommand("Maya", "lights on", 8, false)));
console.log(handlePanel(new VoiceCommand("guest", "unlock the front door", 21, true)));
```

```text
Done: unlock the front door
Stopped: a guest can't unlock doors
Stopped: it's after 22:00, so the speakers stay quiet
Stopped: nobody's home (was that the TV?)
Stopped: a guest can't unlock doors
```

It works today. Now look ahead. Sam's vacation check means opening `handleVoice` and finding the right place in the row of `if`s. If the permission rule changes (Sam may unlock, but only before 22:00), it has to change in two copies, and the second copy is easy to forget. A phone app coming next month needs the permission check and the vacation check, but not the night check: a third copy, slightly different again.

- **The symptom:** one method with a growing, ordered list of checks, and copies of it wherever a slightly different set is needed.
- **The cause:** the checks, their order and the real work ("Done") are welded together in one function. You can't pick up one check and reuse it, and you can't change the order without editing the whole thing.

## What would you try?

**One function per check, called from `handleVoice`.** Tidier: each check has a name. But `handleVoice` still lists them, in order, by name, and each device still has its own hand-written list.

**A flag for each check: `handle(command, night: true, home: true, allowed: true)`.** Now every caller passes three switches, soon four, and the function grows an `if` for every flag.

**Make every device run all the checks.** Simple, but wrong: the wall panel is touched by a hand, so "nobody's home" makes no sense there.

What we want is checks as separate pieces that can be lined up in any order, a different line for each device, with each piece deciding only one thing: stop here, or pass it on.

## The fix: each check passes it along

A coin sorter does exactly this. You pour coins in at the top and they roll down a ramp past a row of slots, smallest first. Each slot takes the coins that fit it; every other coin rolls on to the next slot. The ramp doesn't know which coin you poured, and adding a slot for a new coin doesn't change the others.

![A coin sorter seen from the front: coins roll down a sloping ramp past four slots of growing width; each coin drops through the first slot it fits, and the coins too wide for a slot roll on past it to the next](https://fsdtrainingmedia.blob.core.windows.net/public/images/2026/11/1c04303549c74aa1930e8a86fae85215.webp)

The hub's checks can work the same way. Each check is a **link** in a chain. A link looks at the command and does one of two things: **stops** it, with a reason, or **passes it on** to the next link. The last link, the one that only ever gets a command every check has passed, does the work. The voice handler's chain is night, then someone home, then permission, then "do it". The wall panel's chain is permission, then "do it": the same permission link, reused.

![Chain of Responsibility's roles: the hub hands a voice command to the first of three checks in a row, the night check, the someone-home check and the permission check. Each passes it on or stops it with a reason, and the last one leads to running the command. The checks and their order are fenced](https://fsdtrainingmedia.blob.core.windows.net/public/images/2026/11/ad8eb15cbac54554bb2d12cceb9a7bc6.webp)

Here's a guest's "unlock the front door" moving down the voice chain, as a sequence diagram (*Sequence Diagrams: Who Calls Whom, in Order*):

![A sequence diagram of a guest's "unlock the front door": the hub hands it to the night check, which passes it on to the someone-home check, which passes it on to the permission check, which stops it: "Stopped: a guest can't unlock doors". It never reaches "run the command"](https://fsdtrainingmedia.blob.core.windows.net/public/images/2026/11/63ac3989827d40739ced00459d6a8287.webp)

### The classic version: a link that knows the next link

Every link keeps one promise, `handle(command)`, and holds the next link. Building the chain is nesting them, first link outside:

```csharp
IHandler voice = new NightCheck(new SomeoneHomeCheck(new PermissionCheck(new RunCommand())));
IHandler panel = new PermissionCheck(new RunCommand()); // the same link, reused

Console.WriteLine(voice.Handle(new VoiceCommand("Maya", "unlock the front door", 21, true)));
Console.WriteLine(voice.Handle(new VoiceCommand("guest", "unlock the front door", 21, true)));
Console.WriteLine(voice.Handle(new VoiceCommand("Sam", "play the news", 23, true)));
Console.WriteLine(voice.Handle(new VoiceCommand("Maya", "lights on", 8, false)));
Console.WriteLine(panel.Handle(new VoiceCommand("guest", "unlock the front door", 21, true)));

interface IHandler
{
    string Handle(VoiceCommand command);
}

class NightCheck(IHandler next) : IHandler
{
    public string Handle(VoiceCommand command) =>
        command.Hour >= 22 && command.Words.StartsWith("play")
            ? "Stopped: it's after 22:00, so the speakers stay quiet"
            : next.Handle(command);
}

class SomeoneHomeCheck(IHandler next) : IHandler
{
    public string Handle(VoiceCommand command) =>
        !command.SomeoneHome
            ? "Stopped: nobody's home (was that the TV?)"
            : next.Handle(command);
}

class PermissionCheck(IHandler next) : IHandler
{
    public string Handle(VoiceCommand command) =>
        command.Who == "guest" && command.Words.Contains("unlock")
            ? "Stopped: a guest can't unlock doors"
            : next.Handle(command);
}

// The end of the chain: every check has passed.
class RunCommand : IHandler
{
    public string Handle(VoiceCommand command) => $"Done: {command.Words}";
}

record VoiceCommand(string Who, string Words, int Hour, bool SomeoneHome);
```

```text
Done: unlock the front door
Stopped: a guest can't unlock doors
Stopped: it's after 22:00, so the speakers stay quiet
Stopped: nobody's home (was that the TV?)
Stopped: a guest can't unlock doors
```

```java
record VoiceCommand(String who, String words, int hour, boolean someoneHome) {}

interface Handler {
    String handle(VoiceCommand command);
}

record NightCheck(Handler next) implements Handler {
    public String handle(VoiceCommand command) {
        if (command.hour() >= 22 && command.words().startsWith("play")) {
            return "Stopped: it's after 22:00, so the speakers stay quiet";
        }
        return next.handle(command);
    }
}

record SomeoneHomeCheck(Handler next) implements Handler {
    public String handle(VoiceCommand command) {
        if (!command.someoneHome()) {
            return "Stopped: nobody's home (was that the TV?)";
        }
        return next.handle(command);
    }
}

record PermissionCheck(Handler next) implements Handler {
    public String handle(VoiceCommand command) {
        if (command.who().equals("guest") && command.words().contains("unlock")) {
            return "Stopped: a guest can't unlock doors";
        }
        return next.handle(command);
    }
}

// The end of the chain: every check has passed.
record RunCommand() implements Handler {
    public String handle(VoiceCommand command) { return "Done: " + command.words(); }
}

void main() {
    Handler voice = new NightCheck(new SomeoneHomeCheck(new PermissionCheck(new RunCommand())));
    Handler panel = new PermissionCheck(new RunCommand()); // the same link, reused

    IO.println(voice.handle(new VoiceCommand("Maya", "unlock the front door", 21, true)));
    IO.println(voice.handle(new VoiceCommand("guest", "unlock the front door", 21, true)));
    IO.println(voice.handle(new VoiceCommand("Sam", "play the news", 23, true)));
    IO.println(voice.handle(new VoiceCommand("Maya", "lights on", 8, false)));
    IO.println(panel.handle(new VoiceCommand("guest", "unlock the front door", 21, true)));
}
```

```text
Done: unlock the front door
Stopped: a guest can't unlock doors
Stopped: it's after 22:00, so the speakers stay quiet
Stopped: nobody's home (was that the TV?)
Stopped: a guest can't unlock doors
```

```python
class VoiceCommand:
    def __init__(self, who, words, hour, someone_home):
        self.who = who
        self.words = words
        self.hour = hour
        self.someone_home = someone_home


# Every link keeps the same promise: it has a handle(command) method.
class NightCheck:
    def __init__(self, next_link):
        self.next_link = next_link

    def handle(self, command):
        if command.hour >= 22 and command.words.startswith("play"):
            return "Stopped: it's after 22:00, so the speakers stay quiet"
        return self.next_link.handle(command)


class SomeoneHomeCheck:
    def __init__(self, next_link):
        self.next_link = next_link

    def handle(self, command):
        if not command.someone_home:
            return "Stopped: nobody's home (was that the TV?)"
        return self.next_link.handle(command)


class PermissionCheck:
    def __init__(self, next_link):
        self.next_link = next_link

    def handle(self, command):
        if command.who == "guest" and "unlock" in command.words:
            return "Stopped: a guest can't unlock doors"
        return self.next_link.handle(command)


class RunCommand:
    """The end of the chain: every check has passed."""

    def handle(self, command):
        return f"Done: {command.words}"


voice = NightCheck(SomeoneHomeCheck(PermissionCheck(RunCommand())))
panel = PermissionCheck(RunCommand())  # the same link, reused

print(voice.handle(VoiceCommand("Maya", "unlock the front door", 21, True)))
print(voice.handle(VoiceCommand("guest", "unlock the front door", 21, True)))
print(voice.handle(VoiceCommand("Sam", "play the news", 23, True)))
print(voice.handle(VoiceCommand("Maya", "lights on", 8, False)))
print(panel.handle(VoiceCommand("guest", "unlock the front door", 21, True)))
```

```text
Done: unlock the front door
Stopped: a guest can't unlock doors
Stopped: it's after 22:00, so the speakers stay quiet
Stopped: nobody's home (was that the TV?)
Stopped: a guest can't unlock doors
```

```javascript
class VoiceCommand {
  constructor(who, words, hour, someoneHome) {
    this.who = who;
    this.words = words;
    this.hour = hour;
    this.someoneHome = someoneHome;
  }
}

// Every link keeps the same promise: it has a handle(command) method.
class NightCheck {
  #next;
  constructor(next) { this.#next = next; }
  handle(command) {
    if (command.hour >= 22 && command.words.startsWith("play")) {
      return "Stopped: it's after 22:00, so the speakers stay quiet";
    }
    return this.#next.handle(command);
  }
}

class SomeoneHomeCheck {
  #next;
  constructor(next) { this.#next = next; }
  handle(command) {
    if (!command.someoneHome) return "Stopped: nobody's home (was that the TV?)";
    return this.#next.handle(command);
  }
}

class PermissionCheck {
  #next;
  constructor(next) { this.#next = next; }
  handle(command) {
    if (command.who === "guest" && command.words.includes("unlock")) {
      return "Stopped: a guest can't unlock doors";
    }
    return this.#next.handle(command);
  }
}

// The end of the chain: every check has passed.
class RunCommand {
  handle(command) { return `Done: ${command.words}`; }
}

const voice = new NightCheck(new SomeoneHomeCheck(new PermissionCheck(new RunCommand())));
const panel = new PermissionCheck(new RunCommand()); // the same link, reused

console.log(voice.handle(new VoiceCommand("Maya", "unlock the front door", 21, true)));
console.log(voice.handle(new VoiceCommand("guest", "unlock the front door", 21, true)));
console.log(voice.handle(new VoiceCommand("Sam", "play the news", 23, true)));
console.log(voice.handle(new VoiceCommand("Maya", "lights on", 8, false)));
console.log(panel.handle(new VoiceCommand("guest", "unlock the front door", 21, true)));
```

```text
Done: unlock the front door
Stopped: a guest can't unlock doors
Stopped: it's after 22:00, so the speakers stay quiet
Stopped: nobody's home (was that the TV?)
Stopped: a guest can't unlock doors
```

```typescript
class VoiceCommand {
  who: string;
  words: string;
  hour: number;
  someoneHome: boolean;
  constructor(who: string, words: string, hour: number, someoneHome: boolean) {
    this.who = who;
    this.words = words;
    this.hour = hour;
    this.someoneHome = someoneHome;
  }
}

interface Handler {
  handle(command: VoiceCommand): string;
}

class NightCheck implements Handler {
  #next: Handler;
  constructor(next: Handler) { this.#next = next; }
  handle(command: VoiceCommand): string {
    if (command.hour >= 22 && command.words.startsWith("play")) {
      return "Stopped: it's after 22:00, so the speakers stay quiet";
    }
    return this.#next.handle(command);
  }
}

class SomeoneHomeCheck implements Handler {
  #next: Handler;
  constructor(next: Handler) { this.#next = next; }
  handle(command: VoiceCommand): string {
    if (!command.someoneHome) return "Stopped: nobody's home (was that the TV?)";
    return this.#next.handle(command);
  }
}

class PermissionCheck implements Handler {
  #next: Handler;
  constructor(next: Handler) { this.#next = next; }
  handle(command: VoiceCommand): string {
    if (command.who === "guest" && command.words.includes("unlock")) {
      return "Stopped: a guest can't unlock doors";
    }
    return this.#next.handle(command);
  }
}

// The end of the chain: every check has passed.
class RunCommand implements Handler {
  handle(command: VoiceCommand): string { return `Done: ${command.words}`; }
}

const voice: Handler = new NightCheck(new SomeoneHomeCheck(new PermissionCheck(new RunCommand())));
const panel: Handler = new PermissionCheck(new RunCommand()); // the same link, reused

console.log(voice.handle(new VoiceCommand("Maya", "unlock the front door", 21, true)));
console.log(voice.handle(new VoiceCommand("guest", "unlock the front door", 21, true)));
console.log(voice.handle(new VoiceCommand("Sam", "play the news", 23, true)));
console.log(voice.handle(new VoiceCommand("Maya", "lights on", 8, false)));
console.log(panel.handle(new VoiceCommand("guest", "unlock the front door", 21, true)));
```

```text
Done: unlock the front door
Stopped: a guest can't unlock doors
Stopped: it's after 22:00, so the speakers stay quiet
Stopped: nobody's home (was that the TV?)
Stopped: a guest can't unlock doors
```

Same lines as before. Sam's vacation check is now one new class, slotted into the voice chain where it belongs, and the permission check lives in exactly one place, used by both chains. In Java, each link is a `record` that holds the next link: the shortest class that keeps a promise and holds one value. C#'s `class NightCheck(IHandler next)` is a primary constructor, the same idea.

### The modern version: a list of check functions

Each check really only answers one question: "is there a reason to stop?" That's a function that returns a reason, or nothing. A chain is then a list of them, and one small loop that stops at the first reason:

```csharp
Func<VoiceCommand, string?> night = command =>
    command.Hour >= 22 && command.Words.StartsWith("play") ? "it's after 22:00, so the speakers stay quiet" : null;
Func<VoiceCommand, string?> someoneHome = command =>
    !command.SomeoneHome ? "nobody's home (was that the TV?)" : null;
Func<VoiceCommand, string?> allowed = command =>
    command.Who == "guest" && command.Words.Contains("unlock") ? "a guest can't unlock doors" : null;

var voiceChecks = new List<Func<VoiceCommand, string?>> { night, someoneHome, allowed };
var panelChecks = new List<Func<VoiceCommand, string?>> { allowed };

Console.WriteLine(Handle(new VoiceCommand("Maya", "unlock the front door", 21, true), voiceChecks));
Console.WriteLine(Handle(new VoiceCommand("guest", "unlock the front door", 21, true), voiceChecks));
Console.WriteLine(Handle(new VoiceCommand("Sam", "play the news", 23, true), voiceChecks));
Console.WriteLine(Handle(new VoiceCommand("Maya", "lights on", 8, false), voiceChecks));
Console.WriteLine(Handle(new VoiceCommand("guest", "unlock the front door", 21, true), panelChecks));

string Handle(VoiceCommand command, List<Func<VoiceCommand, string?>> checks)
{
    foreach (var check in checks)
    {
        string? reason = check(command);
        if (reason != null)
        {
            return $"Stopped: {reason}";
        }
    }
    return $"Done: {command.Words}";
}

record VoiceCommand(string Who, string Words, int Hour, bool SomeoneHome);
```

```text
Done: unlock the front door
Stopped: a guest can't unlock doors
Stopped: it's after 22:00, so the speakers stay quiet
Stopped: nobody's home (was that the TV?)
Stopped: a guest can't unlock doors
```

```java
record VoiceCommand(String who, String words, int hour, boolean someoneHome) {}

// Each check gives a reason to stop, or null to pass the command on.
Function<VoiceCommand, String> night = command ->
    command.hour() >= 22 && command.words().startsWith("play") ? "it's after 22:00, so the speakers stay quiet" : null;
Function<VoiceCommand, String> someoneHome = command ->
    !command.someoneHome() ? "nobody's home (was that the TV?)" : null;
Function<VoiceCommand, String> allowed = command ->
    command.who().equals("guest") && command.words().contains("unlock") ? "a guest can't unlock doors" : null;

String handle(VoiceCommand command, List<Function<VoiceCommand, String>> checks) {
    for (Function<VoiceCommand, String> check : checks) {
        String reason = check.apply(command);
        if (reason != null) {
            return "Stopped: " + reason;
        }
    }
    return "Done: " + command.words();
}

void main() {
    List<Function<VoiceCommand, String>> voiceChecks = List.of(night, someoneHome, allowed);
    List<Function<VoiceCommand, String>> panelChecks = List.of(allowed);

    IO.println(handle(new VoiceCommand("Maya", "unlock the front door", 21, true), voiceChecks));
    IO.println(handle(new VoiceCommand("guest", "unlock the front door", 21, true), voiceChecks));
    IO.println(handle(new VoiceCommand("Sam", "play the news", 23, true), voiceChecks));
    IO.println(handle(new VoiceCommand("Maya", "lights on", 8, false), voiceChecks));
    IO.println(handle(new VoiceCommand("guest", "unlock the front door", 21, true), panelChecks));
}
```

```text
Done: unlock the front door
Stopped: a guest can't unlock doors
Stopped: it's after 22:00, so the speakers stay quiet
Stopped: nobody's home (was that the TV?)
Stopped: a guest can't unlock doors
```

```python
class VoiceCommand:
    def __init__(self, who, words, hour, someone_home):
        self.who = who
        self.words = words
        self.hour = hour
        self.someone_home = someone_home


# Each check gives a reason to stop, or None to pass the command on.
def night(command):
    if command.hour >= 22 and command.words.startswith("play"):
        return "it's after 22:00, so the speakers stay quiet"
    return None


def someone_home(command):
    return None if command.someone_home else "nobody's home (was that the TV?)"


def allowed(command):
    if command.who == "guest" and "unlock" in command.words:
        return "a guest can't unlock doors"
    return None


def handle(command, checks):
    for check in checks:
        reason = check(command)
        if reason is not None:
            return f"Stopped: {reason}"
    return f"Done: {command.words}"


voice_checks = [night, someone_home, allowed]
panel_checks = [allowed]

print(handle(VoiceCommand("Maya", "unlock the front door", 21, True), voice_checks))
print(handle(VoiceCommand("guest", "unlock the front door", 21, True), voice_checks))
print(handle(VoiceCommand("Sam", "play the news", 23, True), voice_checks))
print(handle(VoiceCommand("Maya", "lights on", 8, False), voice_checks))
print(handle(VoiceCommand("guest", "unlock the front door", 21, True), panel_checks))
```

```text
Done: unlock the front door
Stopped: a guest can't unlock doors
Stopped: it's after 22:00, so the speakers stay quiet
Stopped: nobody's home (was that the TV?)
Stopped: a guest can't unlock doors
```

```javascript
class VoiceCommand {
  constructor(who, words, hour, someoneHome) {
    this.who = who;
    this.words = words;
    this.hour = hour;
    this.someoneHome = someoneHome;
  }
}

// Each check gives a reason to stop, or null to pass the command on.
const night = (command) =>
  command.hour >= 22 && command.words.startsWith("play") ? "it's after 22:00, so the speakers stay quiet" : null;
const someoneHome = (command) => (command.someoneHome ? null : "nobody's home (was that the TV?)");
const allowed = (command) =>
  command.who === "guest" && command.words.includes("unlock") ? "a guest can't unlock doors" : null;

function handle(command, checks) {
  for (const check of checks) {
    const reason = check(command);
    if (reason !== null) return `Stopped: ${reason}`;
  }
  return `Done: ${command.words}`;
}

const voiceChecks = [night, someoneHome, allowed];
const panelChecks = [allowed];

console.log(handle(new VoiceCommand("Maya", "unlock the front door", 21, true), voiceChecks));
console.log(handle(new VoiceCommand("guest", "unlock the front door", 21, true), voiceChecks));
console.log(handle(new VoiceCommand("Sam", "play the news", 23, true), voiceChecks));
console.log(handle(new VoiceCommand("Maya", "lights on", 8, false), voiceChecks));
console.log(handle(new VoiceCommand("guest", "unlock the front door", 21, true), panelChecks));
```

```text
Done: unlock the front door
Stopped: a guest can't unlock doors
Stopped: it's after 22:00, so the speakers stay quiet
Stopped: nobody's home (was that the TV?)
Stopped: a guest can't unlock doors
```

```typescript
class VoiceCommand {
  who: string;
  words: string;
  hour: number;
  someoneHome: boolean;
  constructor(who: string, words: string, hour: number, someoneHome: boolean) {
    this.who = who;
    this.words = words;
    this.hour = hour;
    this.someoneHome = someoneHome;
  }
}

// Each check gives a reason to stop, or null to pass the command on.
type Check = (command: VoiceCommand) => string | null;

const night: Check = (command) =>
  command.hour >= 22 && command.words.startsWith("play") ? "it's after 22:00, so the speakers stay quiet" : null;
const someoneHome: Check = (command) => (command.someoneHome ? null : "nobody's home (was that the TV?)");
const allowed: Check = (command) =>
  command.who === "guest" && command.words.includes("unlock") ? "a guest can't unlock doors" : null;

function handle(command: VoiceCommand, checks: Check[]): string {
  for (const check of checks) {
    const reason = check(command);
    if (reason !== null) return `Stopped: ${reason}`;
  }
  return `Done: ${command.words}`;
}

const voiceChecks = [night, someoneHome, allowed];
const panelChecks = [allowed];

console.log(handle(new VoiceCommand("Maya", "unlock the front door", 21, true), voiceChecks));
console.log(handle(new VoiceCommand("guest", "unlock the front door", 21, true), voiceChecks));
console.log(handle(new VoiceCommand("Sam", "play the news", 23, true), voiceChecks));
console.log(handle(new VoiceCommand("Maya", "lights on", 8, false), voiceChecks));
console.log(handle(new VoiceCommand("guest", "unlock the front door", 21, true), panelChecks));
```

```text
Done: unlock the front door
Stopped: a guest can't unlock doors
Stopped: it's after 22:00, so the speakers stay quiet
Stopped: nobody's home (was that the TV?)
Stopped: a guest can't unlock doors
```

The same five lines a third time. The chain is now plain data: a new check is one function added to a list, and reordering is moving it in the list. In the classic version each link decides to call the next one; here the loop does it for them, which is simpler but means a check can only say "stop" or "go on". When a link needs to do something *after* the rest of the chain has run (time how long it took, say), it needs the classic shape, where it holds the next link and calls it itself. Pass 4's middleware is exactly that.

## How it got its name

Each link gets its chance to take **responsibility** for the request, and the request travels down the **chain** until one does. Teams kept building this for help systems, approval steps and event handling in window toolkits, so it was written down in the original 1994 book as **Chain of Responsibility**. The book's version stops at the first link that handles the request; the hub's checks stop at the first one that says no. Both are the same shape: one request, a line of handlers, and each one deciding whether to pass it on.

## Where you've already used it

- **An exception** travels up the chain of calls until a `catch` that handles it stops it; every method without one passes it on.
- **Browser events bubble**: a click on a button goes to the button, then its parent, then the page, until some handler stops it with `stopPropagation()`.
- **Web frameworks' middleware** (ASP.NET Core, Express, and the request pipelines in Spring and FastAPI): a request passes through logging, sign-in and error handling before your code sees it. Pass 4 builds one.

## When not to use it

- **When there are one or two checks that never change.** Two `if`s at the top of one method are easier to read than four classes.
- **When every check must run and report.** A sign-up form that should list *all* its problems at once ("name missing, email invalid") isn't a chain that stops; it's a list of checks that all run.
- **When the order is important but nobody can see it.** A chain built in setup code far away from the handler makes "why was this stopped?" a hunt. Keep the chain's construction in one obvious place.

The cost: a request's path is spread over several small pieces, and a request that every link passes on falls off the end, so always end the chain with a link that does something definite.

**How often you'll meet it:** now and then by name; every day as middleware and exceptions (our estimate).

## Check yourself

2 questions to try on the lesson page.

## So what

When a request has to pass a line of checks, and the line keeps growing or differs from place to place, make each check a link that stops the request or passes it on. Each check lives once, each device gets its own line, and the next check is one more link.

## Key terms

- [Chain of Responsibility](https://www.ask-codey.com/glossary/chain-of-responsibility)
- [Code Smell](https://www.ask-codey.com/glossary/code-smell)
- [Coupling](https://www.ask-codey.com/glossary/coupling)

## Cheat sheets

- [Chain of Responsibility: The Coin Sorter](https://www.ask-codey.com/cheat-sheets/dp-chain-of-responsibility-cheat-sheet)

Source: https://www.ask-codey.com/lessons/dp-chain-of-responsibility
