Code-Based Finite State Machines

One way to implement a finite state machine (or "FSM") is to hard-code the rules into executable code. For COBOL, that means the PROCEDURE DIVISION.

Case Structures

A case structure is a programming construct which selects an action according to the value of a variable. For each possible value, the case structure selects a corresponding action (which may be empty).

In COBOL the standard way to implement a case structure is by means of the EVALUATE verb. You can accomplish the same thing, somewhat at the expense of formal elegance, with a series of ELSE IF clauses. The main advantage of EVALUATE is that you can terminate it with a single END-EVALUATE. A long ELSE IF chain may require an equally long END-IF chain.

(In C the switch/case construct serves the same purpose; again, you can use else if instead. Though the same constructs are available in C++ as well, virtual functions are more fashionable.)

Nested Case Structures

For an FSM we must select an action on the basis of two different variables: the state and the event. A simple case structure is not enough.

One solution is to build two levels of case structure. First we branch according to state. Then, possibly in a separate paragraph, the state branches according to event. Alternatively we can branch on event first and then on state.

Two-Variable EVALUATE

COBOL's EVALUATE is unusual because it allows a case-like structure based on two or more variables. You can code EVALUATE STATE ALSO EVENT. For the individual cases, you code something like WHEN 3 ALSO 7, where 3 is the value of STATE and 7 is the value of EVENT. By this means you can account for all the combinations at a single level.

It is not clear that this technique buys you much. Since you have one big list of cases rather than several small lists, it may be more difficult to verify that you have accounted for all the combinations, especially if someone rearranges the cases in a misguided quest for efficiency.

Pros and Cons

Programmers are used to reading procedural code, and may be baffled by the more abstract nature of a table-based FSM. For that reason alone, a code-based FSM may be easier to maintain. In addition, a code-based FSM can readily accomodate a lot of idiosyncrasies which would be awkward to code into a table.

The main problem with a code-based FSM is that it is so easy to mangle. People accustomed to more conventional coding techniques are likely to rearrange the code, add little tweaks here and there, and generally obscure the overall logical structure (which is obscure enough already).


[home]COBOL Home [books]Further reading