The Checklist
A function must pass two tests to be considered “pure”:
- Same inputs always return same outputs
- No side-effects
Let’s zoom in on each one.
1. Same Input => Same Output
Compare this:
To this:
Pure Functions = Consistent Results
The first example returns a value based on the given parameters, regardless of where/when you call it.
If you pass 2
and 4
, you’ll always get 6
.
Nothing else affects the output.
Impure Functions = Inconsistent Results
The second example returns nothing. It relies on shared state to do its job by incrementing a variable outside of its own scope.
This pattern is a developer’s nightmare fuel.
Shared state introduces a time dependency. You get different results depending on when you called the function. The first time results in 6
, next time is 10
and so on.
Which Version’s Easier to Reason About?
Which one’s less likely to breed bugs that happen only under certain conditions?
Which one’s more likely to succeed in a multi-threaded environment where time dependencies can break the system?
Definitely the first one.