Pure function
A pure function is a function whose result depends only on its input and which reads and changes nothing outside: it touches no database, network, files, clock or random numbers. For the same input it always answers the same way, so it is checked with a unit test without mocks: feed the input, compare the result with the expected one. Example: a discount calculated from the order amount is pure, while a function that takes the discount from a database or saves the order is impure. Real code rarely consists of pure functions alone, so the pure part of the logic is separated from the parts that talk to the outside world.
Frequently asked questions
What is a pure function?
A function whose result depends only on its input and which reads and changes nothing outside.How is a pure function different from an impure one?
An impure function depends on something outside its input (a database, the time, a random number) or changes it (a write to a database, a file, an email). So its result may differ between runs.Why are pure functions easy to test?
They need no mocks and no stand: a test feeds the input and compares the result with the expected one in milliseconds, and the result does not depend on the order of runs.How do you get more pure functions?
Separate the computation from the calls to the outside world: first gather the data, then pass it to a pure function and only then save the result.Source: Wikipedia: Pure function
Where it appears · 1
- Quint vs TLA+ · Specs and context