SimpleStateMachine CodePlex Project

I have posted a CodePlex project here that implements a simple, customizable State Machine & miniature runtime. The point of this project was to replace Windows Workflow Foundation in one of our applications as the state machine engine. Windows Workflow foundation is a powerful, robust technology but turns out to be unsupportable overkill if all you are really after is defining and coordinating state transitions in your application. Plus, it can be rather difficult to unit test, even more difficult to version and extend once an application is deployed, and requires all sorts of baggage in the form of database infrastructure and GAC requirements, etc.

Anyway, this library does nothing else besides let you define a set of events, states, and transitions between states when triggered by events, and optionally allows for user defined actions to fire during the initialization or finalization of any or all states.

As for representing the actual state machines there are a few options: A visual designer such as WF provides. The WF designer itself is awful for representing state machines, even simple ones, as it was designed to suit sequential workflows as well and the two kinds of diagrams have different needs. It might be possible to create a visual designer that did the job well, but it would be a big task. Another option is to configure state machines in code using an object model or fluent interface. This would have worked, but it ends up looking pretty ugly after a while and you can’t change your state machines without deploying updated assemblies.

The approach I settled on was to use a DSL, using Boo and Rhino DSL, as described by Ayende Rahien in his (unfinished) book on the subject. The State Machine language itself was inspired by Martin Fowler, who appears also to be writing a book about DSL’s.

An example state machine definition looks like the sample below. It isn’t as snazzy and colorful as the visual designer version you get with WF, but in practice it is much more practical.

workflow "Telephone Call"

trigger @CallDialed
trigger @HungUp
trigger @CallConnected
trigger @LeftMessage
trigger @PlacedOnHold
trigger @TakenOffHold
trigger @PhoneHurledAgainstWall

state @OffHook:
	when @CallDialed             >> @Ringing	
	
state @Ringing:
	when @HungUp                 >> @OffHook
	when @CallConnected          >> @Connected

state @Connected:
	when @LeftMessage            >> @OffHook
	when @HungUp                 >> @OffHook
	when @PlacedOnHold           >> @OnHold
	
state @OnHold:
	when @TakenOffHold           >> @Connected
	when @HungUp                 >> @OffHook
	when @PhoneHurledAgainstWall >> @PhoneDestroyed
	
state @PhoneDestroyed
Advertisements