States are labels assigned to particular sets of circumstances within the application. Although FSMs are often used to model the GUI part of applications, states are not forms, and events are not necessarily Visual Basic events. You generate a set of predefined events from real-world stimuli and apply them as inputs to the FSM to drive it through transitions into different states. Transitions can have arbitrary lists of actions associated with them, and these actions are executed as you drive the FSM from state to state by repeatedly applying events. An FSM is deterministic because each combination of state and event unambiguously defines the next state to move into.
An FSM can be represented as a state transition diagram or as a pair of tables, one table defining the next state to move into when a particular state/event combination is detected and the other table defining a list of actions to be performed along the way.
Figure 13-4 shows an FSM for a program to strip C comments out of a text stream. (Comments in C are delimited by /* and */.)
Figure 13-4 Comment stripper FSM
The bubbles in Figure 13-4 represent states, and the arrows represent transitions between states. Each transition is labeled with the event that stimulates it and the list of associated actions. One state is designated the start state, which is the initial state when the FSM starts to operate. Here is the FSM in tabular form:
|Any other Char||Outside||Outside||Inside||Inside|
|/||N/A||Print "/ "||N/A||N/A|
|Any other char||Print char||Print "/ "|
These tables provide the basis for implementing an FSM as a program. An FSM program has the following elements:
- A static variable to track the current state and a set of constants to represent all available states
- A table or equivalent program network to look up a state/event pair and decide which state to move into
- A set of constants to represent FSM events
- A driver loop that captures real-world events and decodes the state/event pair