Search code examples
language-agnosticfinite-automatastates

Implementation techniques for FSM states


How do you go about implementing FSM(EDIT:Finite State Machine) states? I usually think about an FSM like a set of functions, a dispatcher, and a thread as to indicate the current running state. Meaning, I do blocking calls to functions/functors representing states.

Just now I have implemented one in a different style, where I still represent states with function(object)s, but the thread just calls a state->step() method, which tries to return as quickly as possible. In case the state has finished and a transition should take place, it indicates that accordingly. I would call this the 'polling' style since the functions mostly look like:

void step()
{
  if(!HaveReachedGoal)
  {
    doWhateverNecessary();
    return; // get out as fast as possible
  }
  // ... test perhaps some more subgoals
  indicateTransition();
}

I am aware that it is an FSM within an FSM.

It feels rather simplistic, but it has certain advantages. While a thread being blocked, or held in some kind of while (!CanGoForward)checkGoForward(); loop can be cumbersome and unwieldy, the polling felt much easier to debug. That's because the FSM object regains control after every step, and putting out some debug info is a breeze.

Well I am deviating from my question: How do you implement states of FSMs?


Solution

  • The state Design Pattern is an interesting way of implementing a FSM:

    http://en.wikipedia.org/wiki/State_pattern

    It's a very clean way of implementing the FSM but it can be messy depending on the complexity of your FSM (but not the amount of states). However, the advantages are that:

    • you eliminate code duplication (especially if/else statements)
    • It is easier to extend with new states
    • Your classes have better cohesion so all related logic is in one place - this should also make your code easier to writ tests for.

    There is a Java and C++ implementation at this site:

    http://www.vincehuston.org/dp/state.html