21   What is Purity?

After reading this lesson, you will be able to:

  • Differentiate between pure and impure functions
  • Provide code examples where the use of impure functions can cause unpredicted behavior of your code.

In this lesson, you’ll learn about purity, a fundamental principle of functional programming. In particular, you are going to see that a pure function is total and it has no side effects: do not worry if you do not know what these terms mean, as I’ll explain them in detail later in this lesson. When coding, being able to distinguish between pure and impure functions can help you identifying and prevent bugs in your code. For example, consider the following scenario:

Suppose you are developing the software for a smart thermostat. Your business requirements dictate your thermostat never to reach temperatures below the freezing point of 0 °C (equivalent to 32 °F) as this could damage its mechanical parts. If this happens, your program should trigger an emergency recovery plan which changes the target temperature to a default that the user can configure. You could translate this with the following function:

def  monitorTemperature(current:  Double,  recovery:  Double):  Double  =
    if  (current  >=  0)  current  else  recovery

This function monitorTemperature behaves in different ways depending on the “purity” of its parameters. Let me show you what I mean with an example:

21.1   A definition of Purity

21.2   Differentiating between pure and impure functions

21.3   Summary

21.4   Answers to Quick Checks