Why does purity improve our code?
So far, we have looked into some properties of purely functional code. We’ve also seen some examples of both pure and impure functions. Now, let’s look at what benefits we can expect from writing pure functional code.
Increases the testability of our code
When writing pure functions, your functions will be easier to test. This is a consequence of them being both idempotent and stateless:
- Idempotent: Run functions any number of times and get the same result
- Stateless: Each function will run independently of the state of the system
For idempotence, it’s easy to see how this would be true. In our test suite, if functions were to return different outputs for the same inputs, it would be hard to write tests for that function. After all, if you can’t predict the output of a certain function, you can only guess what value you should be testing for. The benefit of it being stateless might not be immediately...