Visual Studio 2010!

Read now >

View Now
DevSource RSS FEEDS
XML Want an easy way to keep up with breaking tech news? And the Get DevSource headlines delivered to your desktop with RSS.
ADVERTISEMENT
ADVERTISEMENT

 

DevSource.com: Your Source for Visual Studio on Facebook
ADVERTISEMENT
Object-Oriented State Machines
By Jon Shemitz

Rate This Article: Add This Article To:

Object-Oriented State Machines - ' Now You Can Take '
( 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.

Download the code from this article.



 
 
>>> More ASP and .Net Coding Techniques Articles          >>> More By Jon Shemitz