I'll Be Backend
Principles · TypeScript

Inversion of control: replace hand-wired flow with hooks

Write a rule for every job once, and let each job fill in its part.

17 steps5 chapters~7 min at 1.25×#inversion of control#hooks#callbacks#control flow
Language
The lesson plays right here. Pause anywhere, step back, or jump to a step below. Watch the TypeScript video on YouTube Code on GitHub

Watch the narrated video

Every step

Problem

Steps 1–4

Refactor

Steps 5–11

Payoff

Steps 12–13

TypeScript bonus

Steps 14–15

Recap

Steps 16–17

The code: before and after

Before

class ShipmentJob {
  run(shipmentIds: number[]): void {
    console.log("ship: start");
    for (const id of shipmentIds) {
      console.log(`label ${id}`);
    }
    console.log(`ship: done, items: ${shipmentIds.length}`);
  }
}

class RefundJob {
  run(refundIds: number[]): void {
    console.log("refund: start");
    for (const id of refundIds) {
      console.log(`refund ${id}`);
    }
    console.log(`refund: done, items: ${refundIds.length}`);
  }
}

function runNightBatch(): void {
  new ShipmentJob().run([101, 102]);
  new RefundJob().run([7]);
}

runNightBatch();

After

interface BatchStep {
  handle(id: number): void;
}

class BatchRunner {
  run(name: string, ids: number[], step: BatchStep): void {
    console.log(`${name}: start`);
    for (const id of ids) {
      step.handle(id);
      console.log(`audit ${name} ${id}`);
    }
    console.log(`${name}: done, items: ${ids.length}`);
  }
}

class ShipmentJob implements BatchStep {
  handle(id: number): void {
    console.log(`label ${id}`);
  }
}

class RefundJob implements BatchStep {
  handle(id: number): void {
    console.log(`refund ${id}`);
  }
}

function runNightBatch(): void {
  const runner = new BatchRunner();
  runner.run("ship", [101, 102], new ShipmentJob());
  runner.run("refund", [7], new RefundJob());
  runner.run("restock", [55], {
    handle: (id) => console.log(`restock ${id}`),
  });
}

runNightBatch();

Transcript, step by step

Problem

Step 1: Two jobs, two loops Before

These are a warehouse's night batches, and Shipment Job logs a start line, one label per item, and a done line. Refund Job does the same with its own words, a start line, one refund line per item, and a done line. Run Night Batch ships items 101 and 102, then refunds item 7, so the night logs seven lines. Each job was small and written on a different day, so writing the loop out in each one was the shortest path.

Step 2: An audit line per item Change request

Now compliance asks that every batch write one audit line per item, right after the item is handled. The quick way adds an audit line inside Shipment Job's loop, and another one inside Refund Job's loop. It compiles, and the output gains audit ship 101, audit ship 102, and audit refund 7.

Step 3: Every job wires the flow Code smell

The fixed order of a batch, a start line, one call per item, and a done line, is its flow. Here each job wires that flow by hand, so a rule for every batch has to be written into every job. You can see it in the shipment loop here, its audit line here, the refund loop here, and its audit line here. The same audit rule now exists twice, and each new job means pasting it into one more loop. If one copy forgets the audit line, nothing stops it, and that batch runs silently unaudited.

Step 4: Flip who runs the loop Principle

You might extract an audit helper, but each loop would still have to call it. Forget that call in one job, and that batch still runs unaudited. So the loop should live in one place, and each job should only say what happens to one item. The fix flips who runs the loop, so one runner runs it and calls each job.

Refactor

Step 5: Refactor first Back it out

So we take both audit lines back out, and the jobs log their seven lines again. We refactor in small steps with the same output each time, and the audit comes back at the end.

Step 6: Shipment's per-item work Extract Method

In Shipment Job, we extract the label log into its own method, handle, which takes one item id. The loop now calls handle for each id, and the output is the same.

Step 7: Refund's per-item work Extract Method

The same move in Refund Job, so its refund log becomes a handle method too. Its loop calls handle for each id, and both jobs now keep their per-item work in one method.

Step 8: Name the hook Extract Interface

Both handle methods have the same shape, so we extract an interface, Batch Step, with that one method. Both jobs now say implements Batch Step, and the compiler checks each class against it. Handle is now a shape both jobs share, but each job still runs its own loop.

Step 9: A runner owns the flow Extract Class

Now we extract a class, Batch Runner, and move the flow into its run method. It takes a batch name, the ids and a Batch Step, then logs the start line, loops, and logs the done line. Inside the loop, it calls the step's handle for each id. A method the runner calls at a fixed point in its flow is a hook. Shipment Job's run now only hands its name, its ids and itself to the runner. So the loop that calls handle now belongs to the runner, not the job, and that flip is inversion of control. The output still matches the first version, line for line.

Step 10: Refund uses the runner Replace Inline Code with Function Call

Refund Job's run still wrote the same flow by hand, so we replace that code with a call to the runner. It passes refund, its ids and itself, and the output stays the same.

Step 11: Each job is only its hook Inline Method

Both run methods only forwarded to the runner, so we inline them into Run Night Batch and delete them. Run Night Batch builds one Batch Runner and runs ship and refund, each with its ids and a new job. Each job is now only its hook, one handle method that says what happens to one item.

Payoff

Step 12: The audit, take two Payoff

So the audit request from the start can come back in now. It's one line in Batch Runner's loop, right after the step handles the item. The output is the same as the quick version, with audit ship 101, audit ship 102, and audit refund 7. Shipment Job and Refund Job didn't change at all. Where the shipment loop and its audit line stood, there's only a handle method now, and the same goes for refund. The audit rule exists once, in the one loop that every job runs through.

Step 13: A third job Payoff

But the real test is a new job, and Restock Job has only a handle method that logs restock and the id. Run Night Batch runs it with item 55 under the name restock. Restock Job has no loop and no audit line. What does its batch print? Restock 55, then audit restock 55, from the runner's loop. The runner owns the flow and calls each job's hook, so a rule for every batch is one edit in one place. But every job must now fit the runner's one flow, and a job with a different order can't use it. You also read two classes to follow one batch.

TypeScript bonus

Step 14: A class for one log TypeScript bonus

But Restock Job is a whole class, five lines long, for one log line. TypeScript relates types by their members alone, so any object with a matching handle method fits Batch Step.

Step 15: A job as an object literal TypeScript bonus

So the restock job can be an object literal, written right where Run Night Batch runs it. Its handle is an arrow function that logs restock and the id, and the Restock Job class is gone. The output is the same, audit line included, because the runner still calls that handle as the hook. But this job now lives inside Run Night Batch, so no other code can reuse it by name. So use an object literal for a job one place runs, and a named class for a job other code reuses.

Recap

Step 16: Where we started, where we ended Before / after

On the left, each job ran its own flow, with its own start line, loop, and done line. So a rule for every batch, like the audit line, had to be pasted into each loop. On the right, Batch Runner owns the flow and calls each job's hook, with the audit written once. And each job, even the object literal, only fills in what happens to one item.

Step 17: When to reach for it Takeaways

Reach for it when several jobs share one fixed flow and differ only in the work they do per item. Skip it when there's one job, or when the flows really run in a different order. A runner then only adds a second place to read, with nothing shared for it to own. Spot it by the same loop, with the same start and done lines, copied into several classes. And arrays already work this way, because forEach runs the loop and calls the function you pass for each element.