The End of the Elegance

The finite state machine (FSM) notation is simple and elegant, but you’ll run into problems when you try to apply it to real programs. One class of problem, the conditional state transition, is exemplified by the need for validation when you’re unloading forms. For example, if you consider form B’s OK Click event, you can see that the FSM changes state and does the associated actions unconditionally. If you want to do a form-level validation before committing changes, you’ll have a problem. In practice, the solution depends on how far you’re prepared to go in carrying the FSM through into the implementation of your program. For smaller applications, it’s wise to stop at the design stage and just use the state diagram and tables for guidance when writing the program. For more complex programs, you can carry the FSM right through to the implementation, as you’ll see below.

For a pure FSM implementation, you can get around the validation issue by introducing extra states into the machine. Figure 14-8 shows a new state between states 2 and 1 for form B’s OK event. The only difference is that this state is transient because the FSM immediately flips out of it into state 1 or state 2. This happens because you queue an event for the new state before you even get there. Validation states are also required for confirmation, such as when a user tries to abandon an edited form without saving changes.

Figure 14-8 Introducing transient states to avoid conditional transitions