What is a pure function, and why does it matter?
Quick Answer
A pure function's output depends only on its inputs, and it has no side effects — no I/O, no mutation of external state, no randomness or clock. Given the same arguments it always returns the same result. Pure functions are trivial to test, safe to parallelise, and easy to reason about.
A pure function only depends on its arguments and doesn't touch anything outside itself — no database calls, no file writes, no reading the current time, no mutating a shared object. Same inputs, same output, every time. That makes it dead simple to test — you just assert on the return value — and safe to run in parallel. The pattern I try to follow is functional core, imperative shell: keep the decision-making logic pure and deterministic, and push all the messy I/O to a thin outer layer, so most of my tests are fast pure-function tests.
- Impure: reads a file, writes to a database, calls
DateTime.Now, mutates a shared list, throws non-deterministically. - Functional core, imperative shell: keep the business logic pure and push all the I/O to the edges. The core is fast unit tests; the shell is thin integration tests.
- Pass in the clock, the random source, and the data — don't reach out for them — so the function stays testable and deterministic.