Software Design/Create pure functions
Checklist questions:
- Can the function be pure?
- Can the function be idempotent?
Why
editIt's harder to make programming mistakes calling pure functions than impure functions:
- The order in which a pure function is called with respect to other functions (pure or impure) doesn't matter, therefore, calling a pure function "not in the right moment" can't be a mistake.
- A pure function doesn't access any shared state, so there can't be any race conditions due to calling a pure function concurrently with some other function modifying the same state.
- Accidentally calling a pure function multiple times can't disrupt the state of the system. Therefore, this situation should not be even considered a bug, but merely an inefficiency. This property of pure (and idempotent) functions may be seen as reliability.
Pure functions are easier to test[1] because they don't require setting up any state. Functions mutating global state may be impossible to test in parallel which allows completing the whole test suite faster and, therefore, a shorter development feedback cycle.
Why not
editPure functions have more parameters than equivalent impure functions, therefore calls to pure functions may look more cumbersome. There is also a risk of passing wrong arguments.
Conversion of impure functions into pure usually also requires using immutable data structures and, in general, the data organization that implies less mutability and more copying. This may increase the memory usage of the system.
Related
editReferences
edit- ↑ Refactoring: Improving the Design of Existing Code (2 ed.). 2018. ISBN 978-0134757599. https://martinfowler.com/books/refactoring.html. Chapter 11, "Replace Query with Parameter" section