What Is A Pure Function?
A pure function is a functional programming idea. You do not need to learn any new syntax to start writing them. Writing a pure function is a programming style. A function is classed as pure if it meets these two statements:
- Given the same arguments, the function always returns the same result
- A pure function does not change the state of any of its arguments
- A pure function does not depend on any external dependencies
This sounds simple enough, but why bother? If you strive to make as many functions as possible pure, you guarantee that your code:
- Does not have unexpected side-effects.
- Will not break anything else outside the function.
- Guarantees the order of execution
- Unit tests are easier to write
- Caching becomes easier. If the same inputs produce the same outputs, you can easily change the results if the function takes a long time to execute.
- Easier for developers to understand, as all code is self-contained
Should All My Functions Be Pure?
Simple answer, no. It's impossible to write a whole app with pure functions only. With some conscious effort though you will find that when you consciously try to make each function you write pure, you will end up writing more robust code naturally.
For a simple example, say you have a function that has an array as an argument. If you apply one of the out-of-the-box JS functions like splice(), reverse() on it - then your function is impure, as these functions change the underlining array.
When you mutate arguments, your function is called as 'impure'. Impure functions make life harder. Impure functions are harder to unit test so consequentially increase the chance bugs can occur in your code. In the example above, to keep the function pure, you can clone the array that is passed in, performed the mutation and returned the clone. The original array will remain unchanged and the function is pure.
What Are Side-Effects?
If a function is impure, so it either:
- Modifies a mutable data structure
- Modifies an argument
- Calls an API
- Reads from disk, or, a database
- Throws an exception
In your code, sometimes doing these types of operations is inevitable. As I mentioned above, it's impossible to have an app with only pure functions. There is a technical term for these conditions, side-effects.
Side effects should be avoided because they make the behaviour of your functions unpredictable. When a function has no side effects, it can run anytime you want with no qualms. Given the same input, it will return the same output.
Pure Functions Summary
As that simple example demonstrates, when you code, with a bit of conscious effort you can keep your functions pure with some slight refactoring. On a day-to-day basis, if you keep this principle in mind you'll end up writing more robust code.