15 Stateful programs and stateful computations

 

This chapter covers

  • What makes a program stateful?
  • Writing stateful programs without mutating state
  • Generating random structures
  • Composing stateful computations

Since chapter 1, I’ve been preaching against state mutation as a side effect that should be avoided at almost any cost, and you’ve seen several examples of refactoring programs to avoid state mutation. In this chapter, you’ll see how the functional approach works when keeping state is a requirement rather than an implementation detail of your program.

But what’s a stateful program exactly? It’s a program whose behavior differs, depending on past inputs or events.1 By analogy, if somebody says, “Good morning,” you’ll probably mindlessly greet them in return. If that person immediately says, “Good morning” again, your reaction will certainly differ: Why in the world would somebody say “Good morning” twice in a row? A stateless program, on the other hand, would keep answering “Good morning” just as mindlessly as before because it has no notion of past inputs. Every time is like the first time.

In this chapter, you’ll see how two apparently contradictory ideas—keeping state in memory and avoiding state mutation—can be reconciled in a stateful functional program. You’ll then see how functions that handle state can be composed using the techniques you learned in chapter 14.

15.1 Programs that manage state

15.1.1 Caching data in memory

15.1.2 Refactoring for testability and error handling

15.1.3 Stateful computations

15.2 A language for generating random data

15.2.1 Generating random integers

15.2.2 Generating other primitives

15.2.3 Generating complex structures

15.3 A general pattern for stateful computations

Summary