Using FSM Diagrams


I find diagrams like this to be immensely useful for figuring out state machines for subsystems whose behavior is well known. On the other hand, most systems that are amenable to FSMs do not have behaviors that are well known in advance. Rather, the behaviors of most systems grow and evolve over time. Diagrams aren't a conducive medium for systems that must change frequently. Issues of layout and space intrude on the content of the diagrams. This intrusion can sometimes prevent designers from making needed changes to a design. The specter of reformatting the diagram prevents them from adding a needed class or state and causes them to use a substandard solution that doesn't impact the diagram layout.

Text, on the other hand, is a very flexible medium for dealing with change. Layout issues are at a minimum, and there is always room to add lines of text. Therefore, for systems that evolve, I create state transition tables (STTs) in text files rather than STDs. Consider the STD of the subway turnstile in Figure 15-8. This can be easily represented as an STT, as shown in Table 15-1.

Figure 15-8. Subway turnstile STD


Table 15-1. Subway Turnstile STT

Current State

Event

New State

Action

Locked

coin

Unlocked

Unlock

Locked

pass

Locked

Alarm

Unlocked

coin

Unlocked

Refund

Unlocked

pass

Locked

Lock


The STT is a simple table with four columns. Each row of the table represents a transition. Look at each transition arrow on the diagram. You'll see that the table rows contain the two endpoints of each arrow, as well as the event and action of the arrow. You read the STT by using the following sentence template: "If we are in the Locked state and get a coin event, we go to the Unlocked state and invoke the Unlock function."

This table can be converted into a text file very simply:

Locked

coin

Unlocked

Unlock

Locked

pass

Locked

Alarm

Unlocked

coin

Unlocked

Refund

Unlocked

pass

Locked

Lock


These 16 words contain all the logic of the FSM.

SMC (state machine compiler) is a simple compiler I wrote in 1989 to read STTs and generate C++ code to implement the logic. Since then, SMC has grown and changed to emit code for various languages. We'll be taking a much closer look at SMC in Chapter 36 when we discuss the STATE pattern. SMC is freely available from the resources section of www.objectmentor.com.

Creating and maintaining FSMs in this form is much easier than trying to maintain diagrams, and generating the code saves lots of time. So, though diagrams can be very useful to help you think through or present an FSM to others, the text form is much more convenient for development.




Agile Principles, Patterns, and Practices in C#
Agile Principles, Patterns, and Practices in C#
ISBN: 0131857258
EAN: 2147483647
Year: 2006
Pages: 272

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net