State Machines by Dave Thomas (NFJS)
Posted on November 08, 2004 by Scott Leberknight
The first session I attended at the Reston No Fluff Just Stuff conference was "State Machines: Moving Logic into Data" by Dave Thomas. It was, as pretty much all of Dave's presentations, very informative and well done. Dave started with a very simple state diagram and some Java code that represented the various states, transitions, and events. He showed how quickly you can get yourself into trouble using a code-driven approach rather than a data-driven approach, with masses of conditionals within conditionals, switch statements, etc.
We then saw some serious refactoring into a much more practical table-driven approach where the state machine is described in a database table. We then moved into a discussion of the GoF State Pattern and showed how that is not really the best way to implement state machines, and how you end up with some serious code bloat using the State Pattern. We then moved into State Machine Compilers, the specific example being SMC, the State Machine Compiler available on Sourceforge. Interestingly, SMC generates code that follows the State Pattern! Of course, since the code is generated for you, it doesn't matter all that much, precisely since the code is generated for you.
Dave ended the session with four hints. First, make life easy when possible by using strings rather than numbers for states and events. In addition, add debugging hooks on state transitions. Second, states are long lived, meaning state can be stored in a database for long-running business processes. A state is a "stable, quiescent place" until an event occurs which triggers a transition to another state or back to the same state. Third, state machines are business logic. If you put the logic in data not code it is easier to change the logic. This data-driven approach can also allow business users to change the logic by modifying data rather than requiring a code change and redeployment. Fourth, isolate and test. Specifically, separating your state machine from event generation permits separate unit testing of individual transitions using mock events.