3 Why function purity matters

 

This chapter covers

  • What makes a function pure or impure
  • Why purity matters in concurrent scenarios
  • How purity relates to testability
  • Reducing the impure footprint of your code

The initial name for this chapter was “The irresistible appeal of purity.” But if it was so irresistible, we’d have more functional programmers, right? Functional programmers, you see, are suckers for pure functions: functions with no side effects. In this chapter, you’ll see what that means exaclty, and why pure functions have some very desirable properties.

Unfortunately, this fascination with pure functions is partly why FP as a discipline has become disconnected from the industry. As you’ll soon realize, there’s very little purity in most real-world applications. And yet, purity is still relevant in the real world, as I hope to show in this chapter.

We’ll start by looking at what makes a function pure (or impure), and then you’ll see how purity affects a program’s testability and even correctness, especially in concurrent scenarios. I hope that by the end of the chapter you’ll find purity, if not “irresistible,” at least “definitely worth keeping in mind.”

3.1 What is function purity?

3.1.1 Purity and side effects

3.1.2 Strategies for managing side effects

3.1.3 Avoid mutating arguments

3.2 Enabling parallelization by avoiding state mutation

3.2.1 Pure functions parallelize well

3.2.2 Parallelizing impure functions

3.2.3 Avoiding state mutation

3.3 Purity and testability

3.3.1 Isolating I/O effects

3.3.2 A business validation scenario

3.3.3 Why testing impure functions is hard

3.4 Testing code that performs I/O

3.4.1 Object-oriented dependency injection

3.4.2 Testability without so much boilerplate

3.5 Purity and the evolution of computing

3.6 Exercises

3.7 Summary