2004-03-17
| Table of Contents: |
| Rate This Article: | Add This Article To: |
( Page 3 of 3 )
It Further">
State machines often require more state data than simply which handler to invoke next. For example, the whole point of IEnumerator is the CurrentValue. In a one-off state machine, state handlers might be nested within the class that implements IEnumerator, and can thus freely access private fields and private properties. In a more loosely-coupled implementation, you can do as I've done, and build access to the extra state variables into the handlers' interface to the state machine.
One thing you don't need to do is to build an explicit state stack, as you often need to do in an an enum and switch implementation. Each state class contains a NextState field, which can be a "return address" (as in the ShowDirectory and ShowSubdirectories states) or a "forwarding address" (as in the ShowFiles state). In effect, the state classes maintain a sort of distributed stack, in the linked list of ShowDirectory state objects.
Overall, I find that object-oriented state machines are a lot easier to read and debug than their enum and switch equivalents. While there's a certain amount of programming overhead involved in creating a class for each state, this seems to me to be roughly comparable to the amount of overhead involved in updating both an enum and a switch.
While implementing a state machine via state objects is a bit more expensive than using a switch statement, I don't think this matters all that much since most uses of state machines focus on their ability to maintain context across multiple invocations, and speed is not a primary concern.
Jon Shemitz is an independent developer and author in Santa Cruz, California.
![]() |
|


