Lesson 2 of 9 · 20m
Pure Functions, Impure Edges
How to isolate time, randomness, IO, and DOM effects so most of the application remains deterministic and testable.
A pure function is not an academic luxury. It is a function you can test by reading it: same inputs, same output, no hidden conversation with the outside world. Applications exist to perform effects, so purity will never cover the whole system. The profitable design keeps the pure core large and the impure edge thin.
What purity rules out
function impureTotal(items) {
metrics.count("cart.total"); // effect
cache.lastItems = items; // hidden write
return subtotal(items) + taxRate; // hidden read
}This function depends on taxRate and cache state that are not parameters, and it performs work even when the caller only wanted a number. Moving the call site can change behavior. That is what makes impurity expensive: not moral failure, but invisible coupling.
Decision inside, effect outside
function decidePriceRule(user, cart, now) {
if (user.isStaff) return { kind: "discount", percent: 20 };
if (cart.total >= 100 && now.getMonth() === 11) {
return { kind: "discount", percent: 10 };
}
return { kind: "none" };
}
function checkoutHandler(user, cart) {
const rule = decidePriceRule(user, cart, new Date());
paymentClient.applyRule(rule); // impure edge
}decidePriceRule is deterministic because time is input. The effectful shell is tiny and boring, which is exactly what you want from code that touches payment systems.
Dependency injection without ceremony
function loadSettings(readFile, parseJson, path) {
return parseJson(readFile(path));
}Pass narrow capabilities, not giant service objects. readFile is a capability; system is a junk drawer. Wire real implementations at the boundary and fakes in tests.
Referential transparency is a debugging tool
If f(x) always returns the same result for the same x, you can replace the call with its result while reasoning. Once dates, randomness, mutable globals, logging behavior, or IO sneak in, that substitution stops working and every reader must reconstruct hidden context.
Field notes
Date.now(),Math.random(),crypto.randomUUID(), DOM reads, network calls, andlocalStorageare effect sources. Treat them as boundary inputs.- Keep validation, pricing, ranking, scheduling, and transformation logic pure. Put fetch, write, render, and telemetry in the shell.
- A promise-returning function is not automatically harmful; ask whether calling it performs work or merely describes work.
- Temporary diagnostic logging is fine. Persistent behavior-driving logging belongs behind an explicit logger dependency.
Was this lesson helpful?