5 Purity: Avoiding mutable state

 

This chapter covers

  • Problems of writing correct code with mutable state
  • Understanding referential transparency and its relationship to purity
  • Programming without changing values of variables
  • Understanding situations in which mutable state isn’t evil
  • Using const to enforce immutability

We touched on the topics of immutability and pure functions in chapter 1. I said one of the main reasons for the existence of bugs is that it’s hard to manage all the states a program can be in. In the object-oriented world, we tend to approach this issue by encapsulating parts of the program state into objects. We hide the data behind the class API and allow modification of that data only through that API.

This allows you to control which state changes are valid and should be performed, and which shouldn’t. For example, when setting the birthdate of a person, we might want to verify the date isn’t in the future, the person isn’t older than her parents, and so on. This verification reduces the number of states the program can be in to only the states we consider valid. Although this improves the chances of writing correct programs, it still keeps you open to various problems.

5.1 Problems with the mutable state

Let’s check out the following example. A movie_t class contains the movie name and a list of scores the users gave it. The class has a member function that calculates the average score for this movie:

5.2 Pure functions and referential transparency

 
 
 

5.3 Programming without side effects

 
 
 

5.4 Mutable and immutable state in a concurrent environment

 
 
 

5.5 The importance of being const

 
 

5.5.1 Logical and internal const-ness

 
 

5.5.2 Optimizing member functions for temporaries

 
 
 
 

5.5.3 Pitfalls with const

 
 
 
 

Summary

 
 
sitemap

Unable to load book!

The book could not be loaded.

(try again in a couple of minutes)

manning.com homepage
test yourself with a liveTest