21 What is purity?

 

After reading this lesson, you will be able to

  • Differentiate between pure and impure functions
  • Provide code examples in which impure functions cause unpredicted code behavior

In this lesson, you’ll learn about purity, a fundamental principle of functional programming. In particular, you’ll see that a pure function is total and has no side effects. Distinguishing between pure and impure functions can help you identify 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) because it could damage its mechanical parts. If this happens, your program should trigger an emergency recovery plan that changes the target temperature to a default value 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. Consider the following function invocations:

scala> monitorTemperature(current = 5, recovery = 10)
val res0: Double = 5.0
 
scala> monitorTemperature(
        | current = 5,
        | recovery = { println("EMERGENCY! Triggering recovery"); 10 }
        | )
 
EMERGENCY! triggering recovery
val res1: Double = 5.0

21.1 A definition of purity

21.2 Differentiating between pure and impure functions

Summary

Answers to quick checks

sitemap