Monday, April 11, 2011

The State of things

The humble state machine has been implemented many many times, but enums are no longer the way to do it.

At the heart of things, you have some information about our current condition or state, and you have things that can happen, ie Events.

Some Events are valid for our current state, some are not.

If we use an object to record our state, then the object can have member functions to deal with events.

So, if we start with an AbstractState which cares about Enable, Disable, Pause, and Continue events. We give it virtual functions for each of these and in each case, we throw an "Invalid Event For State" exception, detailing the Name of the Current State and the Event.

Our Enabled State, derives from this, and implements Disable, and Pause.

IState Disable() {
  return DisabledState; // this is just a static instance.
}

IState Pause() {
  return PausedState; // this is just a static instance.
}

If you try to "Continue" an Enabled State, then you get an exception

For each state, you override the functions to deal with the possible events.

To process an Enable event, your code then calls

currentState = currentState.Enable();

And so on.

Do exercise care in deciding that you cannot go from state A to state B. Someone may take a personal dislike to you and all your children based on some artificial restriction that you enforce.

No comments:

Post a Comment