State

AKA: objects for states

At some point, the logic in an object might become cumbersome, branching on attributes implying state. As those implicit states become essential to how the program runs across more and more methods, the chance for mistakes increases. Instead of using these implicit states, we migrate to an enum. But then we have introduced a switch into our code. These are often a sign of a non-extendable design.

Instead, we want to continue growing the program to completion but are aware of the risks of these state variables. It would be better to encapsulate the state in some way where it did not need to use a switch but still could transition as before.

To do this, our Stateful object changes its implicit class by holding onto an instance with the desired behaviour, a State object. The State object has a collection of methods as per the Adapter pattern, but each method also receives a context, the Stateful object.

The State object is itself stateless. It can be a Singleton. When a State object detects the need to change the state of the Stateful outer object, it does so via the context parameter.

I avoid the presented implementation of this pattern as I find it more complicated than helpful. Instead, I prefer when a State object returns a new state object (or itself) on every call. The returning variant allows the State object to have some state of its own. It can hand over any information to its replacement State and doesn’t need to know anything about its owner object. This way, you can have more than one state per object.

“I am, therefore I think.”