A toy figure assessing the level of water in a mason jar using a tape measurer.

A pure function:

  1. has no side effects.
  2. always produces the same output for a given input.

Pure functions are known to be easy to test. We can use their characteristics to make all code easier to test.

Don’t mix logic and side effects in the same method

Even if you don’t write functional code, this is good practise. When separated from the rest you can test the logic to your hearts content, and create a single integration test for the side effects. We need side effects, but keep them isolated and in methods without conditionals.

Inject your dependencies

If everything that might vary is part of the input, the output can be deterministic. In contrast, letting the method have access to collaborators and state “behind the scenes”, creates variance that is independent of the input. That will make for more setup in the tests, and more combinations to cover.

Pure functions remove some of the hardest part from testing, you can use that knowledge in all software development.

Related texts

A single frosted leaf with clear contours and veins.

TDD in the context of writing code to be read

Wunder Baum hanging from a car window (Known as Little Trees in most English-speaking countries)

Wunderbaum testing