When is a function pure?

Function_machine2.svgFunctional programming evolves around functions and a pure function is a very important aspect. But when exactly is function pure? I’ll try to show when a function is pure with some examples.

The following function is pure because no external state is touched and every time the function is called with the same parameters the result will be the same.

public function add(Integer x, Integer y) {
  return x + y;

When the result of a function is different with each call the function is not pure (or impure). Using the random generator will make the following function impure.

public function generateId() {
  return Math.random();

Updating some non-local variable also will make the function impure. The following function is impure because of the non-local variable and also because the result will vary every invocation.

public function inc() {
  return this.counter;

Using pure functions has some advantages that are worth the effort. Some of the advantages are:

  • Testability; Every function can be unit tested with a elegant and concise unit test. Because a function cannot introduce side effects and the result can be easily predicted the unit test can be very simple.
  • Memoizable; When a function is used often in a program the result can be cached and looked up in a table. This can only be done when the function is pure and the function does not call another impure function.
  • Parallelism; Functions can be executed on different processors because they don’t share state.

So to give a sum