Pure Functions and Predictable Results

A pure function produces a result determined by its inputs and has no observable effects on the surrounding program.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Isolate the decision
  2. Move variable input outside
  3. Check repeated calls and shared inputs
  4. Watch for mutation behind convenient operations

Isolate the decision

A price calculation that receives unit price and quantity can compute the total without reading a clock, database, or global discount. For seven times three it always returns twenty-one under ordinary integer arithmetic. This is different work from emitting output, even when the same caller requests both.

Move variable input outside

If the price depends on an active promotion, supply the promotion as another input. The same function can be tested with or without it. Follow the advice on reproducing a run to identify any other hidden inputs.[1][2]

Check repeated calls and shared inputs

A function converting centimetres to metres can calculate length / 100 from its argument alone. A pricing function that looks up a changing exchange rate performs another kind of calculation even if it returns a number of the same type. To isolate the calculation, pass the rate as an argument. Then eighty units at a rate of 1.25 yield one hundred on every call given those inputs. See dependency arguments for how to supply data or a provider explicitly.

Watch for mutation behind convenient operations

A median helper that sorts the caller's list in place can return the correct median three for [8, 1, 3] while changing the list to [1, 3, 8]. If the caller uses arrival order later, its behavior changes. Use a sorted copy when the input must stay unchanged, and test both the result and the input after calling. Inputs reachable through nested references may also change if a shallow copy shares elements. See in-place sorting and sorted copies and shallow copies.

References

  1. Python Software Foundation, Python Tutorial: Control Flow ↩
  2. Python Software Foundation, Python Language Reference: Execution Model ↩