...

/

Different Strategies for Implementing State Machines

Different Strategies for Implementing State Machines

In this lesson, we will explain the different strategies for implementing state machines.

Every non-trivial program passes through several different states during its lifecycle. Describing this lifecycle as a finite state machine is a simple and useful abstraction. This lesson investigates different strategies for implementing state machines. The goal is to identify mechanisms that let the code communicate the intent of expressing the problem as a finite state machine.

Traditional Solution with Conditionals

Consider a simple, digital stop-watch. In its most basic version, it has two states: started and stopped. A traditional and direct way to implement this behavior in C is with conditional logic in the shape of switch/case statements and if-else chains.

In this example, the digital stop-watch is implemented as a First-Class ADT.

Press + to interact
typedef enum
{
stopped,
started
} State;
struct DigitalStopWatch
{
/* Let a variable hold the state of our object. */
State state;
TimeSource source;
Display watchDisplay;
};
void startWatch(DigitalStopWatchPtr instance)
{
switch(instance->state)
{
case started:
/* Already started -> do nothing. */
break;
case stopped:
instance->state = started;
break;
default:
error("Illegal state");
break;
}
}
void stopWatch(DigitalStopWatchPtr instance)
{
switch(instance->state)
{
case started:
instance->state = stopped;
break;
case stopped:
/* Already stopped -> do nothing. */
break;
default:
error("Illegal state");
break;
}
}

This is a ...