State

The world persists. If a minute ago the sun was high in the sky, you can be sure it is still high in the sky, but moved a bit. If I cared to calculate, I could predict its new position based on my previous observation, knowledge of the earth’s rotation, and measurement of the passage of time.

Thinking of the world as things that change has proven useful for a long time. The Native Americans in the area where I live watched Mt. McLaughlin in the spring. When the snow melted sufficiently that the outline of a flying eagle appeared in the remaining snow, it was time to move down to the Rogue River to catch the spring run of salmon. The state of the snow on the mountain was a valuable clue to the presence of a yummy meal swimming in the water some distance away.

When computing pioneers picked metaphors for programming computers, they latched onto this idea of state changing over time. The human brain has a wide variety of strategies, built-in and learned, for dealing with state.

However, state also poses problems for programmers. As soon as you assume what some bit of state is, your code is at risk. You might assume incorrectly or the state might change. Many desirable programming tools, like automated refactorers, are easier to construct if there is no notion of state.

Finally, concurrency and state don’t play well together. Many of the problems of parallel programs vanish if there is no state.

Functional programming languages dispense altogether with changing state. None of these has ever become popular. I think state is a valuable metaphor for us since our brains are structured and conditioned to deal with changing state. Single assignment or variableless programming forces us to discard too many effective thinking strategies to be an attractive choice.

Object languages are a coping strategy for dealing with state. They offer the opportunity to avoid the problem of state changing “behind your back” by partitioning the state in the system into discrete little chunks, each of which has strictly limited access to the others. It is easier to keep track of a handful of bytes than mega- or gigabytes. The problem of incorrectly assuming the value of some state remains, but with objects you have the chance to quickly and accurately review all access to a variable.

A key to managing state effectively is putting similar state together and making sure different state stays apart. Two clues that two bits of state are similar are if the two bits are used in the same computation and if the two bits live and die at the same time. If two pieces of state are used together and have the same lifetime, then having them close to each other is probably a good idea.

Implementation Patterns

contents