Finite State Machine Pattern - The One True Pattern?

hooleyhoop picture hooleyhoop · Feb 16, 2011 · Viewed 9.4k times · Source

Could all Code ever written be improved by applying the State Machine Pattern?

I was working on a project that was a mass of horrendous awful, buggy, broken spaghetti code. I copied Martin Fowler's example State Machine code from this blog and transformed the whole heap of crap into a series of statements. Literally just a list of States, Events, Transitions and Commands.

I can't believe the transformation. The code is now clean, and works. Of course i was aware of State Machines before and have even implemented them but in the Martin Fowler example the separation of model/configuration is amazing.

This makes me think that almost everything i've ever done could have benefitted in some way from this approach. I want this functionality in every language i use. Maybe this should even be a language level feature.

Anyone think this is wrong? Or anyone have a similar experience with a different pattern?

Answer

Pontus Gagge picture Pontus Gagge · Feb 16, 2011

Finite state machines (FSM's) and more specifically domain specific languages (DSL's) make it easier to match a problem to one specific solution domain, by describing the solution in a specialised language.

The limitations of the State Machine pattern is that it itself constitutes a programming language, but one for which you have to write your own execution, testing and debugging tools; and one which any maintainer has to learn. You have moved the complexity of your code into a complex FSM configuration. Occasionally, this is useful, but certainly not universally.

And since any von Neumann computer is itself a FSM, then certainly any program can be recast in this fashion.