Pure Functions

Pure functions are mathy.

The sine function, sin(x), from your high school trigonometry class, is a pure function. The absolute value function is a pure function. Heck, adding two numbers together is a pure function.

Pure functions follow two rules:

  1. No side effects. A pure function takes an input and returns an output, and has no effects elsewhere.

  2. A pure function always returns the same thing for a given input. An addition function, given the inputs 2 and 3, never produces something other than 5.

Why should you care?

Rule number one means you can be confident that when you call a pure function, you won’t affect state elsewhere. It doesn’t write to a log or update a record in a database, or anything like that.

Rule number two means you can be confident that when you call a pure function, state elsewhere won’t affect you. Your result doesn’t change based on a configuration file or a property from another module, or anything like that.

This confidence makes pure functions easy to reason about. With no dependencies and no side effects to juggle, your brain is freed up to focus on the single thing your function is tasked with.

Pure functions lend themselves to simpler tests, too. With no dependencies to set up and no side effects to check, tests for a pure function tend to follow a simple pattern: send data into the function, check for the expected output.