Skip to content

Lesson 10 of 28Keeping code healthy

Functional Core, Imperative Shell

Put every business decision in pure functions over immutable data, push I/O to a thin shell, and make illegal states impossible to write.

19 min read0/4 questions

The refund endpoint has a bug: customers who received their parcel are getting the restocking fee waived. To write a test that reproduces it, you need a database with an order in it, a fake payments client, a frozen clock, and an HTTP test client. Forty lines of setup for a rule that fits in five. Then you fix it and the test is so slow and brittle that nobody adds the next case. The problem is not the bug. It is that the decision (how much to refund) is welded to the actions (read the DB, call the payment provider, write the DB). This lesson shows how to cut them apart, and the handful of functional ideas that make the cut stay clean.

Pure functions and the hidden inputs

A function is pure when two things hold: its output depends only on its arguments, and calling it changes nothing outside it. Call it twice with the same arguments and you get the same answer, so you can replace the call with its result. That property has a name, referential transparency, and it is what makes pure code easy to reason about.

Most impurity comes from inputs that are not in the signature:

  • The clock: datetime.now() or Date.now() inside a rule means the answer changes every time you run the test.
  • Randomness: uuid4(), random(), Math.random().
  • Global and environment state: os.environ, a module-level settings object, a singleton cache.
  • I/O: the database, the network, the file system, a logger.

And most side effects are outputs that are not in the return value: writing a row, sending an email, mutating an argument that the caller still holds.

Pure functions pay off in four concrete ways. Tests are just "these values in, this value out", with no mocks. Results can be cached safely (memoisation works because the same input always means the same output). Calls can run in parallel, because there is no shared state to race on. And bugs reproduce: if you log the inputs, you can replay the exact decision on your laptop.

Quick check
Which of these functions is pure?
Need a nudge? A hint rules out a wrong answer.

Functional core, imperative shell

Gary Bernhardt named the pattern in his 2012 talk Boundaries. Split every feature into two parts:

  • The functional core: pure functions over plain data. All the decisions live here: is this refund allowed, how much, what is the new state. No imports of your web framework, ORM or HTTP client.
  • The imperative shell: a thin layer that gathers inputs (read the DB, read the clock, parse the request), calls the core, and executes what the core decided (write the DB, call the provider, return a response). It has almost no if statements of its own.

The core has many paths and no dependencies, so you test it with dozens of fast unit tests. The shell has few paths and many dependencies, so you test it with a handful of integration tests. That matches the testing pyramid by construction.

Here is the tangled version of the refund endpoint, in FastAPI.

before: app/routes/refunds.py
@router.post("/orders/{order_id}/refund")
def refund(order_id: int, body: RefundIn, db: Session = Depends(get_db)):
    order = db.get(OrderRow, order_id)
    if order is None:
        raise HTTPException(404)
    remaining = order.total_cents - order.refunded_cents
    if body.amount_cents > remaining:
        raise HTTPException(422, "too much")
    if datetime.now(timezone.utc) - order.paid_at > timedelta(days=30):
        raise HTTPException(422, "too late")
    payout = body.amount_cents
    if order.status == "delivered":
        payout -= body.amount_cents // 10
    stripe.Refund.create(payment_intent=order.payment_intent, amount=payout)
    order.refunded_cents += body.amount_cents
    db.commit()
    return {"refunded_cents": payout}

Every rule in there sits between a database read and a payment call. Now the same feature, split. The core is decide_refund(order, requested, now), which returns a decision value: either Approve (with the payout and the new order state, computed but not saved) or Deny (with a reason). The shell reads, decides, and acts.

Python
from dataclasses import dataclass, replacefrom datetime import datetime, timedelta, timezonefrom typing import Literal # ---------- FUNCTIONAL CORE: data in, decision out. No I/O, no clock, no globals.@dataclass(frozen=True)class Order: id: int total_cents: int paid_at: datetime status: Literal["paid", "shipped", "delivered"] refunded_cents: int = 0 @dataclass(frozen=True)class Approve: payout_cents: int reason: str updated: Order # the new state, computed but not saved @dataclass(frozen=True)class Deny: reason: str RefundDecision = Approve | DenyREFUND_WINDOW = timedelta(days=30)RESTOCKING_FEE_PCT = 10 def decide_refund(order: Order, requested_cents: int, now: datetime) -> RefundDecision: remaining = order.total_cents - order.refunded_cents if remaining == 0: return Deny("nothing left to refund") if not 0 < requested_cents <= remaining: return Deny(f"amount must be between 1 and {remaining}") if now - order.paid_at > REFUND_WINDOW: return Deny("outside the 30-day window") updated = replace(order, refunded_cents=order.refunded_cents + requested_cents) if order.status == "delivered": fee = requested_cents * RESTOCKING_FEE_PCT // 100 return Approve(requested_cents - fee, "restocking fee applied", updated) return Approve(requested_cents, "full refund", updated) # Testing the core needs no mocks, only values.t0 = datetime(2026, 5, 1, tzinfo=timezone.utc)cases = [ (Order(1, 5000, t0, "paid"), 5000, t0 + timedelta(days=2)), (Order(2, 5000, t0, "delivered"), 5000, t0 + timedelta(days=10)), (Order(3, 5000, t0, "paid"), 5000, t0 + timedelta(days=31)), (Order(4, 5000, t0, "paid", refunded_cents=4000), 2000, t0),]for order, amount, now in cases: d = decide_refund(order, amount, now) print(order.id, type(d).__name__, d.reason, getattr(d, "payout_cents", "")) # ---------- IMPERATIVE SHELL: gather inputs, call the core, act on the decision.class FakeDb: def __init__(self, orders): self.orders = {o.id: o for o in orders} def get(self, oid): return self.orders.get(oid) def save(self, o): self.orders[o.id] = o class FakePayments: def __init__(self): self.refunds = [] def refund(self, oid, cents): self.refunds.append((oid, cents)) def refund_endpoint(db, payments, clock, order_id: int, amount_cents: int) -> tuple[int, dict]: order = db.get(order_id) # I/O in if order is None: return 404, {"error": "not found"} decision = decide_refund(order, amount_cents, clock()) # pure decision match decision: # I/O out case Approve(payout_cents=payout, updated=new_order): payments.refund(order.id, payout) db.save(new_order) return 200, {"refunded_cents": payout} case Deny(reason=why): return 422, {"error": why} db, pay = FakeDb([Order(7, 8000, t0, "delivered")]), FakePayments()clock = lambda: t0 + timedelta(days=3)print(refund_endpoint(db, pay, clock, 7, 8000))print(refund_endpoint(db, pay, clock, 7, 1))print(refund_endpoint(db, pay, clock, 99, 1))print(pay.refunds)
Output
Press Run (⌘ Enter) to see what happens.

Notice three things. The clock arrives as an argument, so the 30-day rule is tested with exact dates, no freezing libraries. The core returns the new order instead of mutating the old one, so the shell decides whether and when to persist it. And the shell's match has one branch per decision: no business rule is hiding in it. In the real FastAPI version the shell is the route function plus a repository, and it shrinks to about ten lines.

One refund request through shell and core
Route (shell)Databasedecide_refund (core)Payments APIget order 7Order(...)order, 8000, nowApprove(7200, updated)refund 7200save(updated)

The shell does all the reading first: the order from the DB, now from the clock, the amount from the request body.

1/6
Put it in order5 steps

Order the work inside a well-shaped imperative shell for one request.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

What if the decision needs data halfway through, like "if the order is over 1,000, check the fraud score"? Two options. Load it up front if it is cheap. Otherwise split the core into two pure steps and let the shell fetch between them: needs_fraud_check(order) -> bool, then decide_refund(order, fraud_score, now). The shell stays a straight line of fetch, decide, fetch, decide, act.

Immutability, and where mutation is still fine

A pure core works on immutable values. If a function cannot change its input, nobody has to wonder whether it did. In Python, @dataclass(frozen=True) makes assignment raise, dataclasses.replace(obj, field=...) builds a modified copy, and tuple and frozenset are the immutable collections. In TypeScript, readonly fields and readonly T[] stop writes at compile time, as const freezes a literal's type, and Object.freeze stops writes at run time.

All of these are shallow. A frozen dataclass holding a list still lets anyone append to that list, and Object.freeze does not freeze nested objects. Use immutable types all the way down for core data.

Predict the outputPython

What does this print?

from dataclasses import dataclass, replace

@dataclass(frozen=True)
class Cart:
  items: tuple
  tags: list

a = Cart(items=("mug",), tags=["new"])
b = replace(a, items=a.items + ("cap",))
b.tags.append("sale")
print(len(a.items), a.tags)
Need a nudge? Hints walk you through it.

Copying a whole object for every change sounds slow. In practice copies are shallow and small, and libraries like Immer (used by Redux Toolkit) and persistent collections use structural sharing: the new version reuses every unchanged part of the old one and only copies the path that changed. React's state model depends on exactly this, which is why setItems([...items, x]) works and items.push(x) does not trigger a render.

Mutation is fine when nobody else can see it. A local list you build inside a function and return is invisible to callers, so the function is still pure from the outside. Hot loops that process millions of rows should mutate a local buffer. The rule is: no shared mutable state, not "never mutate".

Make illegal states unrepresentable

The phrase is Yaron Minsky's. If your types allow a state that makes no sense, some code path will eventually produce it. The classic example is UI fetch state stored as three independent fields: isLoading, error, data. That is eight combinations, and only four mean anything. "Loading with an error and stale data" is a bug waiting for a render.

A discriminated union (TypeScript) or tagged union (Python dataclasses plus Literal and match) allows exactly the legal states, and each state carries only the fields it can have. Unions and Narrowing in the JavaScript & TypeScript course covers the mechanics; here is the design payoff, together with a pure reducer that moves between states.

TypeScript
// BEFORE: three independent flags allow 8 combinations; only 4 make sense.type LooseState = { isLoading: boolean; error: string | null; data: string[] | null };const nonsense: LooseState = { isLoading: true, error: "timeout", data: ["a"] }; // compiles fineconsole.log("loose state allows:", JSON.stringify(nonsense)); // AFTER: one discriminated union. Each state carries only the data it can have.type RemoteData<T> = | { readonly status: "idle" } | { readonly status: "loading" } | { readonly status: "failure"; readonly error: string; readonly retryable: boolean } | { readonly status: "success"; readonly data: readonly T[] }; function render(state: RemoteData<string>): string { switch (state.status) { case "idle": return "Search for something"; case "loading": return "Loading..."; case "failure": return state.retryable ? `Error: ${state.error} (retry)` : `Error: ${state.error}`; case "success": return state.data.length ? state.data.join(", ") : "No results"; default: { const unreachable: never = state; // add a fifth status and this line stops compiling return unreachable; } }} // A pure reducer: old state + event -> new state. Never mutates.type SearchEvent = | { type: "search" } | { type: "loaded"; items: readonly string[] } | { type: "failed"; error: string }; function next(state: RemoteData<string>, event: SearchEvent): RemoteData<string> { switch (event.type) { case "search": return { status: "loading" }; case "loaded": return { status: "success", data: event.items }; case "failed": return { status: "failure", error: event.error, retryable: event.error === "timeout" }; }} const events: readonly SearchEvent[] = [ { type: "search" }, { type: "failed", error: "timeout" }, { type: "search" }, { type: "loaded", items: ["mug", "cap"] },];let state: RemoteData<string> = { status: "idle" };console.log(render(state));for (const e of events) { state = next(state, e); console.log(render(state));} const ROLES = ["viewer", "editor", "admin"] as const; // readonly tuple of literal typestype Role = (typeof ROLES)[number]; // "viewer" | "editor" | "admin"const canEdit = (r: Role) => ROLES.indexOf(r) >= ROLES.indexOf("editor");console.log(ROLES.map((r) => `${r}:${canEdit(r)}`).join(" "));
Output
Press Run (⌘ Enter) to see what happens.

The never line is the senior move. When someone adds a "stale" status next year, every switch that forgot to handle it fails to compile, instead of silently rendering nothing. In Python, a type checker such as mypy or Pyright gives you the same check when a match uses assert_never from typing in its final case _: branch.

Parse, don't validate

Alexis King's 2019 essay gave this idea its name. Validation checks input and throws the result away: if is_valid_email(s): send(s). The value is still a plain str, so every function downstream has to wonder whether it was checked, and many re-check "to be safe". Parsing checks input and returns a new, more precise type: parse_email(s) -> Email. Once you hold an Email, it is valid by construction, and the type system carries that proof everywhere.

Do it once, at the edge of the shell. In FastAPI that edge is a Pydantic model on the route; in TypeScript it is a Zod (or Valibot, or ArkType) schema's parse or safeParse on the request body. Inside, the core accepts only the parsed types and never re-checks.

This ties directly to errors as values. Exceptions are right for bugs and broken infrastructure: a null you did not expect, a database that is down. Nobody can handle those locally, so let them fly to a top-level handler. But "the user typed a bad email" or "the refund is outside the window" are expected outcomes, part of the business. Returning them as values (Ok / Err, Approve / Deny) puts them in the signature, so callers cannot forget them and tests can assert on them directly. Rust's Result and TypeScript libraries like neverthrow formalise this; in Python, two frozen dataclasses and match are enough.

Python
import refrom dataclasses import dataclassfrom typing import Generic, TypeVar T = TypeVar("T") @dataclass(frozen=True)class Ok(Generic[T]): value: T @dataclass(frozen=True)class Err: field: str message: str Result = Ok[T] | Err # ---- Value types that can only exist if valid@dataclass(frozen=True)class Email: value: str @dataclass(frozen=True)class Quantity: value: int @dataclass(frozen=True)class OrderRequest: email: Email sku: str quantity: Quantity # ---- Parsers: raw input in, typed value or an error value outdef parse_email(raw: object) -> Result[Email]: if not isinstance(raw, str) or not re.fullmatch(r"[^@\s]+@[^@\s]+\.[a-z]{2,}", raw.strip().lower()): return Err("email", "not a valid email") return Ok(Email(raw.strip().lower())) def parse_quantity(raw: object) -> Result[Quantity]: if isinstance(raw, bool) or not isinstance(raw, int) or not 1 <= raw <= 99: return Err("quantity", "must be a whole number from 1 to 99") return Ok(Quantity(raw)) def parse_order(body: dict) -> Result[OrderRequest]: email = parse_email(body.get("email")) qty = parse_quantity(body.get("quantity")) for r in (email, qty): if isinstance(r, Err): return r return Ok(OrderRequest(email.value, str(body.get("sku", "")), qty.value)) # ---- The core trusts its types. No re-checking deep inside.def confirmation_line(req: OrderRequest) -> str: return f"{req.quantity.value} x {req.sku} for {req.email.value}" for body in [ {"email": " Ada@Example.com ", "sku": "MUG-1", "quantity": 2}, {"email": "ada@", "sku": "MUG-1", "quantity": 2}, {"email": "ada@example.com", "sku": "MUG-1", "quantity": True},]: match parse_order(body): case Ok(value=req): print("200", confirmation_line(req)) case Err(field=f, message=m): print("422", f, "->", m)
Output
Press Run (⌘ Enter) to see what happens.

The third case is a real trap: in Python True is an int subclass, so a naive isinstance(raw, int) accepts "quantity": true from JSON as 1. Parsing in one place means you fix that in one place.

Composition replaces whole class hierarchies

Once rules are pure functions over values, you can build bigger behaviour by composing small functions instead of subclassing. A higher-order function takes or returns a function (the Python course has a whole lesson on them). You saw in Design Patterns Overview that Strategy collapses to a function; a pipeline of such functions replaces Chain of Responsibility and much of Command too, and because the rules are data you can choose and order them from config.

Python
from functools import reducefrom typing import Callable Price = int # centsRule = Callable[[Price], Price] def pipeline(*steps: Rule) -> Rule: return lambda x: reduce(lambda acc, step: step(acc), steps, x) # Each rule is a tiny pure function. A "strategy" is just one of them.def percent_off(pct: int) -> Rule: # a higher-order function: returns a rule return lambda p: p - p * pct // 100 def minus(cents: int) -> Rule: return lambda p: max(p - cents, 0) def floor_at(cents: int) -> Rule: return lambda p: max(p, cents) # Rules are data, so you can choose and order them from config, per customer.PLANS: dict[str, Rule] = { "basic": pipeline(), "member": pipeline(percent_off(10)), "promo": pipeline(percent_off(10), minus(500), floor_at(1000)),}for plan, rule in PLANS.items(): print(f"{plan:<7} {rule(4000):>5} {rule(1200):>5}")
Output
Press Run (⌘ Enter) to see what happens.

Order matters in a pipeline exactly as it does in a chain of if statements: floor_at(1000) placed first would do nothing useful. Keep pipelines short and named, because a 15-step anonymous pipeline is as hard to debug as a 15-level class hierarchy.

When the pattern stops paying

Functional core is a direction, not a religion. A pure CRUD endpoint (read a row, return it) has no decision to extract, so there is no core to write. Workflows that interleave many dependent I/O calls, like a saga across three services, can end up with a shell that is mostly orchestration; keep each step's decision pure and accept that the orchestration is imperative. Deep immutability in a hot numeric loop costs real time, so mutate locally there. And a team new to these ideas will read reduce pipelines slower than a plain for loop, so use the plain loop when it is clearer. The point is not to avoid side effects. It is to know exactly where they are.

Match the pairs0/5 matched

Match each problem to the functional technique that fixes it.

Choose an item, then its match on the other side.
Key terms
pure function
A function whose result depends only on its arguments and that changes nothing outside itself.
functional core, imperative shell
Pure functions make every decision; a thin outer layer does the I/O and executes those decisions.
referential transparency
A call can be replaced by its result without changing the program, which is true of pure functions.
discriminated union
A type that is one of several variants, told apart by a literal tag field such as status.
parse, don't validate
Turn raw input into a precise type once at the boundary, so inner code never has to re-check it.
structural sharing
Building a new immutable version that reuses every unchanged part of the old one.
errors as values
Returning expected failures as part of the result type instead of throwing exceptions.