A crash course in UML state machines: Part 3
To read Part 1, go to "The over simplification of the event-action paradigm"
To read Part 2, go to "UML extensions to the traditional FSM formalism"
Designing a UML state machine, as any design, is not a strict science. Typically it is an iterative and incremental process: You design a little, code a little, test a little, and so on. In that manner you may converge at a correct design in many different ways, and typically also, more than one correct HSM design satisfies a given problem specification.
To focus the discussion, here I walk you through a design of an UML state machine that implements correctly the behavior of a simple calculator similar to the Visual Basic calculator used at the beginning of this series. Obviously, the presented solution is just one of the many possible.
Figure 2.13: A simple electronic calculator used as a model for the statechart example.
Problem specification
The calculator (see Figure 2.13) operates broadly as follows: a user enters an operand, then an operator, then another operand, and finally clicks the equals button to get a result. From the programming perspective, this means that the calculator needs to parse numerical expressions, defined formally by the following BNF grammar:
expression ::= operand1 operator operand2 '='
operand1 ::= expression | ['+' | '-'] number
operand2 ::= ['+' | '-'] number
number ::= {'0' | '1' | ... '9'}* ['.' {'0' | '1' | ... '9'}*]
operator ::= '+' | '-' | '*' | '/'
The problem is not only to correctly parse numerical expressions, but also to do it interactively ("on the fly"). The user can provide any symbol at any time, not necessarily only the symbols allowed by the grammar in the current context. It is up to the application to ignore such symbols. (This particular application ignores invalid inputs.
Often an even better approach is to actively prevent generation of the invalid inputs in the first place by disabling invalid options, for example.) In addition, the application must handle inputs not related to parsing expressions, for example Cancel (C) or Cancel Entry (CE). All this adds up to a nontrivial problem, which is difficult to tackle with the traditional event-action paradigm (see part 1 of this article series) or even with the traditional (nonhierarchical) FSM.


Loading comments... Write a comment