Pure functions and the imperative shell
Relay retries failed jobs, and the function that decides when looks harmless. It reads the clock,
adds a random delay so a thousand jobs do not retry in the same millisecond, bumps the attempt
counter and logs what it did. In production it worked. In tests it needed a fake Date, a seeded
Math.random, a spy on console.log, and still the test for “gives up after five attempts” was flaky.
M6 rebuilds Relay’s processing pipeline so that decisions are plain functions from values to values, and side effects happen in one thin layer at the edge. This lesson shows the split on the retry planner. The later lessons build the tools that make the split comfortable.
What a pure function is
Section titled “What a pure function is”A function is pure when two things hold. Its result depends only on its arguments, and calling it
does nothing except compute that result. Here is Relay’s first planRetry:
interface MutableJob { id: string attempt: number}
function planRetry(job: MutableJob): number | null { if (job.attempt >= 5) { console.log(`give up ${job.id}`) return null } job.attempt += 1 const jitter = Math.floor(Math.random() * 1000) return Date.now() + 1000 * 2 ** job.attempt + jitter}The signature says “job in, number or null out”. The body also reads the clock, reads a random source, writes to the console and changes the caller’s object. None of that is visible to the caller or to the type checker.
Hidden inputs and hidden outputs
Section titled “Hidden inputs and hidden outputs”Everything a function reads that is not in its parameters is a hidden input: Date.now(),
Math.random(), process.env, a module-level variable, a database row. Everything it does that
is not in its return value is a hidden output: logging, mutating an argument, writing a file,
and also throw, because the caller’s control flow changes in a way the return type does not show.
Hidden inputs make tests depend on the world. Hidden outputs make the caller unable to reuse or
reorder calls. Relay’s mutation was the real bug: the dispatcher called planRetry twice for the
same job while building a log line, and the job’s attempt count jumped by two.
Replace the call by its value
Section titled “Replace the call by its value”The practical test for purity is called referential transparency: you may replace any call by the value it returns, and the program means the same thing.
const delay = (attempt: number): number => 1000 * 2 ** attempt
const a = delay(3) + delay(3)const b = 8000 + 8000// a and b are the same program. If delay logged or counted calls, they would not be.console.log(a === b)This is what lets you cache a result, move a call out of a loop, run two calls in either order or run them in parallel without asking what else they touch. It is also what lets you read a function without reading its callers.
Turn inputs into parameters, outputs into return values
Section titled “Turn inputs into parameters, outputs into return values”The fix is mechanical. Each hidden input becomes a parameter. Each hidden output becomes part of the return value, as data describing what should happen:
interface Job { readonly id: string readonly kind: "email" | "slack" | "http" readonly payload: string readonly attempt: number}
type RetryDecision = | { readonly _tag: "GiveUp"; readonly reason: string } | { readonly _tag: "RetryAt"; readonly at: number; readonly job: Job }
function planRetry(job: Job, now: number, jitter: number): RetryDecision { if (job.attempt >= 5) return { _tag: "GiveUp", reason: `attempt ${job.attempt} exceeds limit` } const delay = 1000 * 2 ** job.attempt + Math.floor(jitter * 1000) return { _tag: "RetryAt", at: now + delay, job: { ...job, attempt: job.attempt + 1 } }}The clock and the dice are now arguments, so a test passes 1000 and 0.5 and compares the
result with toEqual. The log line is gone from the function: the decision carries the reason,
and whoever acts on it decides whether to log. The job is not changed, a new one with
attempt + 1 is returned. The decision is a discriminated union,
so the caller must handle both cases.
Functional core, imperative shell
Section titled “Functional core, imperative shell”The effects still have to happen somewhere. Put them in a small function that gathers the inputs, calls the pure core and carries out the decision:
interface Job { readonly id: string readonly attempt: number}type RetryDecision = | { readonly _tag: "GiveUp"; readonly reason: string } | { readonly _tag: "RetryAt"; readonly at: number; readonly job: Job }declare function planRetry(job: Job, now: number, jitter: number): RetryDecision
interface ShellDeps { now(): number random(): number log(message: string): void schedule(job: Job, at: number): void}
function runRetry(deps: ShellDeps, job: Job): void { const decision = planRetry(job, deps.now(), deps.random()) switch (decision._tag) { case "GiveUp": deps.log(`give up ${job.id}: ${decision.reason}`) return case "RetryAt": deps.schedule(decision.job, decision.at) deps.log(`retry ${job.id} at ${decision.at}`) return }}The shell has no logic worth testing: read, call, act. The core has all the logic and no effects.
ShellDeps is the same idea as the ports of M5. The difference is where the
line falls: ports isolate the effects, and the core does not even receive them. Most of Relay’s
bugs lived in the decisions, so most of its tests are now plain expect(plan(x)).toEqual(y) with
no fakes at all.
The rest of M6 follows this shape. Immutable updates keep the data safe to share. Algebraic data types model decisions and rules. Later lessons make failure and absence into values, and the capstone makes the effects themselves values.
Exercise
Section titled “Exercise”Make Relay’s retry planner pure. planRetry(job, now, jitter) returns a decision and touches
nothing, and runRetry is the shell that reads the clock and the dice, calls it and acts on the
result. The starter’s planRetry always gives up and runRetry does nothing.
- A pure function depends only on its arguments and does nothing but return a value.
- Hidden inputs (clock, randomness, environment, globals) and hidden outputs (logging, mutation,
throw) are what make a function impure. - If you can replace a call by its result without changing the program, the call is referentially transparent.
- Turn each hidden input into a parameter and each hidden output into data in the return value.
- Keep a thin imperative shell that reads inputs, calls the pure core and performs the decision.