Chapter 4

Pure Functions: The Original Abstraction

Same inputs, same output. No exceptions. No surprises. No lies.
Demo: Order-Independent Composition: 6 permutations, same functions, different order
☠ Class methods: order matters
Permutation 1
addItem → applyCoupon → calcTax
Permutation 2
applyCoupon → addItem → calcTax
Permutation 3
calcTax → addItem → applyCoupon
Permutation 4
addItem → calcTax → applyCoupon
Permutation 5
applyCoupon → calcTax → addItem
Permutation 6
calcTax → applyCoupon → addItem
✦ Pure functions: order irrelevant
Permutation 1
calc_total → apply_coupon → calc_tax
Permutation 2
apply_coupon → calc_total → calc_tax
Permutation 3
calc_tax → calc_total → apply_coupon
Permutation 4
calc_total → calc_tax → apply_coupon
Permutation 5
apply_coupon → calc_tax → calc_total
Permutation 6
calc_tax → apply_coupon → calc_total
0/6
Results match (class)
0/6
Results match (function)

What you just saw

Six permutations of the same three operations. On the left, class methods that mutate shared fields produce different results depending on call order. applyCoupon before addItem calculates the discount against a stale total. calcTax before applyCoupon taxes the full amount. The class cannot protect you from calling methods in the wrong order because every method reads and writes the same mutable fields.

On the right, pure functions produce identical results regardless of order. Each function takes its inputs explicitly and returns a new value. No function can see or affect another function's computation. The composition is order-independent because there is no shared state to corrupt.

This is the property that ensures correctness. It eliminates the entire class of bugs that arise from "this must happen before that." It is more important than encapsulation, more important than polymorphism, and it is the foundation that makes safe parallel execution trivial.

How this works: This demo visualizes a correctness property, not timing. Mutable methods that read shared state produce different results depending on call order (1 of 6 permutations correct). Pure functions that take all data as arguments produce the same result in any order (6 of 6 correct). Source: github.com/adamzwasserman/honest-code-traces
← Ch.3: Data Is Just Data Ch.5: State Has an Address →