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 ...

Get Functional Programming in C++ now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.