Statecharts: Some Critical Observations: 2 Uses of Hierarchy
Statecharts: Some Critical Observations: 2 Uses of Hierarchy
Michael Breen
1
viewed comfortably on the screen or printed on a
single page. X X
However, one should not assume that this kind
of abstraction will add to the model’s understand- p p
ability; indeed adverse results reported by one
group of users led them to advocate minimizing p p
the number of layers of abstraction [5]. In fact, it Y Y
can be argued that there is a general problem with
abstraction in finite state machine models as com- H
pared to models of other kinds [1]. Below, I de-
A A
scribe an error that would have been much more
difficult to detect had abstraction been used.
q (in Y) q
Transition Dependence
q (in Y) q
Figure 1 (a) shows two orthogonal components. B B
The transitions in one are dependent on the other
being in state Y. Figure 1 (b) shows how hierar-
chy may be used to show this dependency visually.
Note the use of the history mechanism to ensure (a) (b)
the state of the second component (whether A or
B) is remembered. Figure 1: Hierarchy with history.
The fundamental problem with history is that it
confuses the two otherwise quite distinct concepts has a history entrance then this assumption is in-
of hierarchy and parallelism (or orthogonality): As valid since a parallel state machine has effectively
emphasized by the need to remember the “previ- been hidden at a lower level. By mixing up hi-
ous” substate of the superstate with a history en- erarchy and parallelism, the function of memory
trance, the substates are properly regarded as those is shared between states and histories and the in-
of a component with an existence independent of tegrity of the concept of a state is weakened.
the superstate. The effect of an apparently innocu-
ous little circle with a ‘H’ is completely to trans-
State Variable Instantiation
form the semantics of the substate-superstate rela-
tionship. Hierarchy may also be used to, in effect, instantiate
Consider a statechart in which all the states are a new finite state machine (in statecharts terminol-
superstates whose contents have been abstracted ogy, an orthogonal component). Figure 2 shows a
and are shown only on separate diagrams. Sup- stopwatch taken from the example in [3]. In this
pose there are two orthogonal components, one case, the stopwatch is described either by a single
with states A and B, the other with states X and Y. state if it is stopped and reset to zero or by two
Now if the system is in states A and X then to de- states, one to indicate whether it is stopped or run-
scribe the overall state of the system at a finer level ning and the other to tell us whether it is displaying
of detail one could normally assume one needs to the elapsed time or the last lap time.
consider only the substates of these. After all, A Instantiation of finite state machines is normally
and B, for example, are mutually exclusive and so done above the level of the finite state model. One
the substates of B should not be relevant. But if B may, for example, model the behaviour of an ob-
2
stopwatch many states in the model of [3]. However, we
zero could also make display and run orthogonal com-
ponents at the top level of the model (we might
then call the former stopwatch-display-mode since
d (in off) b it reflects the actual display only in state stop-
watch); in the full digital watch there is a deep his-
display run tory entrance to stopwatch and so the nesting of
states within stopwatch is really a way to make the
reg on transitions between them conditional on being in
this state.
d In the digital watch example there are two other
(in on) d b b cases of orthogonal components appearing within
a state (that is, other than at the top level - which
lap off is not really a state as such). One is to model beep
test functionality, wherein the watch beeps if two
buttons are pressed at the same time. Again, a state
can always be associated with this function so that
we may say it really belongs at the top level: when-
Figure 2: Stopwatch state of digital watch. ever the system is not in the superstate containing
the beep-test component, the beep test is implicitly
in an inactive state.
ject using a statechart and indicate in a higher level The other use is in order to model a state dead
diagram or other description that one or more in- which corresponds to the battery being removed or
stances of that object can exist and specify when exhausted. Because of this, all the other orthogo-
these are created and deleted. Although this is gen- nal components, which would otherwise be at the
erally a more flexible and powerful approach, it top level and so always exist, are shifted down one
seems unsuitable in the case of the stopwatch. For level into an alive state. Once again, this does not
example, if the statechart completely models the mean that no state can be associated with these
state of the stopwatch for some of the time with components: If the battery is dead then clearly the
a single state variable (stopwatch) then it seems light is off, the beep test is inactive, the display is
preferable for it to continue to do so even when blank, and so on. Further, modeling the state dead
two (display and run) are needed. really serves no purpose other than to demonstrate
However, the stopwatch example is not actually the notation. If the statechart is to serve as a de-
one in which a need suddenly arises for an addi- sign for the internal logic of the watch then clearly
tional variable to model the state: In state zero, the state dead does not belong in the model. If its
the stopwatch is not running and it is displaying purpose is to describe or specify the external be-
the elapsed time (which happens to be zero) and haviour of the watch then including the state dead
so this state really represents a combination of the is hardly more useful than including a state like
two state aspects otherwise modeled separately by broken.
the display and run components. The stopwatch In the digital watch example there are no cases
model could be replaced, for example, by either of where the creation of orthogonal components on
those in Figure 3. entry to a superstate corresponds to any need for
Of course, in these alternatives, display and run an additional state variable, that is, one that has no
are still instantiated on entry to stopwatch, one of meaning outside that superstate. In the author’s ex-
3
stopwatch stopwatch
display run display run
zero
d (in off) /
reset time
d on on
(in off) b
reg
reg
b b b b
d
(in on) d
d off off
(in on) d
lap
lap
(a) (b)
perience, this is always the case and so alternatives are familiar; one needs to know that in state zero
to statecharts, such as the ordinary state transition the stopwatch does not run in Figure 2 as well as
diagram, do not suffer in comparison. in Figure 3 (a).
This application of hierarchy would be more
Expression of a Constraint useful if all constraints were always modeled. In
that case, the model would supply all the infor-
The real effect of putting the state zero on a sepa-
mation on what state configurations were possible.
rate level, as in Figure 2, rather than keeping all the
For example, one could tell at a glance from Fig-
states on the same level, as in Figure 3 (a), is to ex-
ure 2 that there were a total of five possible state
press a constraining relationship: In state zero, the
configurations in the stopwatch: zero and the four
stopwatch must not be running, that is, component
combinations of the states from the display and run
run must be in state off. In Figure 3 (a) it is per-
components. If it was subsequently found, perhaps
haps not immediately clear that this constraint is
through an automated check, that it was not possi-
satisfied. In Figure 2, the state zero in effect mod-
ble for display to be lap when run was on then this
els not only the state of the display component but
could be flagged as an error (to be corrected either
also that of the run component; consequently the
by making this configuration reachable or by re-
constraint is satisfied by the semantics of the state
placing the orthogonal components with three sep-
itself.
arate states).
Of course, the clarity of the expressed constraint
then depends on knowing the semantics of the Unfortunately, if the model is more complex
combined state. The interpretation of the state zero then specifying the possible state configurations
in Figure 2 is obvious only because stopwatches within the statechart may lead to a fairly intricate
4
diagram. There may be more states and many pose in the time state that one of the two buttons
more transitions, including branching transitions to activate the beep test is pressed, causing beep-
perhaps with multiple branches where several par- test to enter (say) state 10. The time of an alarm
tially independent aspects of the system state are is reached causing the watch to enter alarms-beep.
involved. Compared to the alternative of simply The user now releases the first button (this has no
modeling separate orthogonal components at the effect) and presses the second button, causing a re-
top level without attempting to explicitly indicate turn to state displays. Because of the deep-history
which combinations of their states are possible (at entrance, the watch is again in state time and beep-
least within the statechart), this use of hierarchy test is again in state 10 – indicating that the first
may be judged undesirable or even impractical. As button is still pressed (which it isn’t) and that the
long as this may be so in specific instances, it can- second button is not currently pressed (which it is).
not be made a general convention. Pressing the first button now fails to activate the
beep test. Alternatively, if the second button is re-
leased and pressed again then the beep test is incor-
3 Subtlety rectly activated without pressing the first button.
Presented as in Figure 4, this error becomes ob-
Adjectives like “concise,” “subtle” and “powerful” vious. However, it was not initially apparent to this
seem to describe statecharts pretty well. In general, author even after a fairly close examination and
these may be regarded as positives. For example, was only detected when converting the model into
conciseness is obviously preferable to useless rep- another notation. The error would be even more
etition and many people enjoy subtlety. These at- difficult to detect if the contents of the time su-
tributes are strongly related to the relatively high perstate had been abstracted and shown only in a
degree of structuring possible in statecharts which lower level statechart – for it would not be present
means that a single aspect of a statechart model can in either statechart considered separately. By using
have broad implications for behaviour. powerful constructs which affect the behaviour in
To show the power of statecharts, Harel de- many different cases it is possible to create a very
scribes how easy it is to add a beep-test function to concise model. Unfortunately, as in this instance,
his digital watch model. To test the beep, the user it also becomes easier to overlook unexpected im-
keeps two buttons pressed at the same time. This is plications.
easily modeled by a beep-test component with four It is possible to identify other unusual scenar-
states: one in which neither button is pressed, two ios involving the beep test function in which the
in which one of the buttons is pressed and another response is questionable but, unlike the previous
in which both buttons are pressed and the watch example, not obviously erroneous. This is an-
beeps; the transitions between these states occur other problem with subtlety: Is the behaviour in
on pressing and releasing the buttons. To neatly a particular case deliberate or is it an unintended
express the fact that the beep test only operates in side effect of structure introduced for some other
certain states, it is made an orthogonal component purpose? This is not a problem if the statechart
within a superstate which encloses those states. is merely a design but if it is also the specifica-
Harel then works through a scenario to demon- tion then one must consult those who created the
strate that the model works as expected. model. If they are available and can remember or
However, this change also introduces an error. at least agree on the correct response then perhaps
Figure 4 shows the position of beep-test within the one might compensate for the model’s subtlety by
overall model (many other states and orthogonal recording their answer so that at least no one else
components are omitted from this diagram). Sup- will need to ask the same question. But would it
5
displays alarms-beep
*
H
time
beep-test
00
10 01
beep
have been better if the specification had been in a (and broadcast events) means the parts may be re-
more explicit form to begin with? lated in relatively complex ways. To check and to
better understand one part of the model, one makes
detours to other parts and after several detours one
4 Amenability to Inspection may lose track of what relationships have been
considered thoroughly and what has been merely
To discover errors like that described above, one understood.
must perform simulations, either mentally or with Also, it is easier to detect an error which is
computer assistance, to see the response of the present in the model than an error of omission (un-
model in various scenarios. However, this is ef- less it is a major one). A statechart model is always
fectively testing and for a complex model it is nor- formally complete and remembering to check that
mally impractical to test all sequences of events all the necessary responses are included is difficult
which might expose an error. when one is busy checking the transitions which
Further, while the graphical nature of state- are present.
charts allows rapid random access to information,
it does not naturally invite or support systematic
review. In trying to proceed methodically through 5 The Rubik’s Cube Effect
the states and transitions, the experience of this au-
thor is that the mind is easily led by the eye; to In statecharts, states are arranged in a strict hierar-
complete a comprehensive more-or-less linearly- chy so that each state may be a substate of at most
ordered review in the face of a fundamentally un- one immediate superstate. It would often be con-
ordered model is difficult. It is not enough to check venient to violate this rule. To take a simple exam-
each part separately as the hierarchical structure ple, if one is clustering states to reduce the number
6
of transitions then states A, B and C might share conditions in which this transition is allowed.
the same exit but C, D and E may respond identi- After the gross structural change, one may there-
cally to some other event. As they overlap on state fore need to make further adjustments to cancel
C, one cannot cluster both groups into superstates. out such side effects. The overall change then
When hierarchy may also be used for other pur- comprises a number of steps. Following our anal-
poses, the number of competing alternatives like ogy, these steps may be likened to the sequence of
this increases. moves one must remember in order to reverse the
While recognising some semantic issues, Harel temporary disorder induced in a partially-solved
was originally convinced that allowing states to Rubik’s Cube. Furthermore, if one omits a step
overlap would greatly enhance statecharts [3]. or makes some other mistake in the changes then
However, in spite of repeated requests for this from it may be much less obvious in the statecharts than
users, later work indicated that extending the no- would be a square of the wrong colour on one side
tation in this way required definitions which were of the cube; the side effect described in the previ-
too complex for it to be generally recommended ous paragraph is one that might easily be missed.
[4]. (Note also that is somewhat incompatible with The point is that during specification one should
using hierarchy for abstraction.) be less concerned with structural issues. Anything
To construct a statechart model one must there- too much resembling the solving of a puzzle con-
fore decide on a unique hierarchy from the com- stitutes design and is best kept as a separate ac-
peting alternatives one can imagine. In a complex tivity. One may then concentrate on establishing
model, what seems at first to be the best choice the facts of the behaviour first without the distrac-
might appear less desirable as modeling advances. tion of having to continually work out how best
This is especially likely where the model is being to alter the statecharts to efficiently represent this
constructed as part of a specification process since behaviour and checking that the model does suc-
one does not initially know all the details of be- cessfully capture one’s intentions. Though design
haviour to be included. itself may remain a challenge, design decisions are
Though the analogy is obviously exaggerated, a at least deferred until they can best be made, that
statechart model, as a relatively structured entity, is, when all the facts are known.
may be compared to a Rubik’s Cube: In the course
of solving the cube, it is necessary to disrupt partial
solutions; and as more of the existing structure em- 6 Broadcast Events
bodies the desired configuration it becomes more
difficult to incorporate new changes. Similarly, in A well-known criticism of statecharts is of broad-
a statechart one may, for example, realise that all cast events between orthogonal components. Com-
of the transitions between the states of component pared to models in which directed communication
A should be made dependent on the system being between separate parallel state machines are shown
in a particular state X of an orthogonal component. on a higher level diagram, broadcast events make it
To model this, one might move the states of A to more difficult to see the relationship between dif-
make them substates of X and add a history en- ferent parts of the model. The same criticism can
trance to this state. However, one then finds that a be made of the capability to refer in the condition
third component is disrupted by this change: One of a transition to the state of another component.
of its transitions contains the condition in Y where Of course, modularity can be restored very simply
Y is a substate of A – but even with history the sys- by limiting the use of orthogonality in a statechart
tem can no longer be “in” Y unless it is also in X and instead using separate statechart models which
and so a side effect of the change is to alter the communicate where necessary by directed events;
7
the broadcast events and states within each one are carry the promise of something that can easily be
invisible to the others. understood by following the arrows, it provides an
opportunity to create something which is not only
logically correct but also aesthetically pleasing.
7 Understandability The use of subtlety allows one to create a cun-
ning and efficient model. Even if one is aware
Event sequencing and priority can be a source of
that one’s primary objective is to describe the be-
confusion in a statechart. If two transitions may be
haviour rather than to find the most efficient repre-
triggered by the same event, which is taken first?
sentation, there is no denying the immediate satis-
The answer may affect the overall response. What
faction of finding a neat way to model something.
if a transition between substates of a superstate and
a transition from the superstate itself may be taken? However, if the same subtlety leads to an error,
Issues of causality and synchrony involving con- most practitioners – who might well object to using
ditions on events can also arise. Even if the se- a less visually appealing but ultimately more effec-
mantics prescribes a unique response and this is tive approach – are likely simply to blame them-
remembered and understood by the reader, trac- selves for making the mistake. Once seen, an error
ing through a causal sequence may be difficult and in a statechart model is easily understood; one per-
lead to errors. Of course, part of the problem is not haps feels a little foolish for having missed it; the
the absence of a precise semantics but the presence model is duly fixed and, lo, the fix can also be un-
of dozens of alternative ones (some of these were derstood. Such errors are regarded as a fact of life
surveyed in [8]; others have been proposed since which reviews and testing are there to find. An er-
then). In general, the modeler is well advised to ror which is somehow discovered after testing in-
keep the statecharts simple enough to avoid situa- dicates a flaw also in the tests (even though test-
tions where confusion may arise. ing every possibility is usually impractical). Fur-
ther, since errors are much less likely in relatively
simple models, it is easy to attribute them to the
8 Why are Statecharts Popular? size and complexity of the model. Overall, one is
unlikely to link errors to the relative subtlety of a
The popularity of statecharts in the academic world given model, associated in its construction with a
can be attributed to the interesting problems posed sense of satisfaction; much less to link them to any
by the notation’s semantics and the seemingly end- more general cognitive issues with the notation.
less potential for modifications and alternatives
which semanticists like to propose and explore.
Many variations have been proposed and entire 9 Conclusions
theses have been written on the subject, filled with
(to the practitioner) obscure theoretical results. The problems described above will not be signifi-
Nevertheless, most semantics are broadly con- cant in relatively simple models. Some issues also
sistent with the intuitive, operational interpretation affect other notations though perhaps to a lesser de-
of a practitioner working with a typical statechart. gree. For example, even if hierarchy is not used,
The addition of hierarchy to the ordinary state tran- it may be necessary to restructure a model where
sition diagram brings more power and flexibility it becomes apparent that a single state machine
(if this power is akin in some respects to that of a would be preferable to two parallel ones which be-
“goto” statement in a programming language then come too interdependent.
this at least is not obvious). The graphical rep- However, many problems relate particularly to
resentation is also an attraction. Not only does it the hierarchical structuring of states unique to stat-
8
echarts. Of the identified uses of this feature, clus- [3] D. Harel, “Statecharts: a visual formalism for
tering to reduce the number of transitions in a dia- complex systems,” Science of Computer Pro-
gram is the most convincing. Using hierarchy for gramming, vol. 8, pp. 231–274, July 1987.
abstraction also seems useful in order to limit the
size of statecharts for practical reasons. However, [4] D. Harel and C.-A. Kahana, “On statecharts
there should be less need for this if parallel state with overlapping,” ACM Transactions on Soft-
machines are modeled using separate statecharts in ware Engineering and Methodology, vol. 1,
the first place rather than orthogonal components no. 4, pp. 399–421, Oct. 1992.
or nesting within a state using the history mecha- [5] N. G. Leveson, M. P. Heimdahl, H. Hildrith,
nism – the most dubious of the uses of hierarchy. and J. D. Reese, “Requirements specification
Many of the above criticisms apply to the use for process-control systems,” IEEE Transac-
of statecharts for specification rather than design. tions on Software Engineering, vol. 20, no. 9,
However, statecharts are generally regarded as a Sept. 1994.
specification notation (and indeed as a kind of for-
mal method of specification). An advertisement [6] N. G. Leveson, M. P. Heimdahl, and J. D.
for one of the tools supporting statecharts claims Reese, “Designing specification languages for
that the statechart specification serves also as the process-control systems: Lessons learned and
design, allowing one to skip the design phase of a steps to the future,” in Proc. ESEC/FSE ’99,
project. An alternative view, consistent with ob- 7th European Software Engineering Confer-
servations above, is that to use statecharts in this ence held jointly with the 7th ACM SIGSOFT
way is in effect to go straight to design, skipping Symposium on the Foundations of Software
specification. Engineering, 6–10 Sept. 1999.
The direction of some research has been towards [7] N. Leveson, M. Heimdahl, H. Hildreth,
simplifying statecharts to make them more suitable J. Reese, and R. Ortega, “Experiences using
for specification [2]; however, it is interesting that statecharts for a system requirements specifi-
one extended research effort into the specification cation,” in Proc. Sixth International Workshop
of process control systems began by using state- on Software Specification and Design, 1991.
charts, modified the notation, and ultimately pro-
posed a completely different approach [7, 5, 6]. [8] M. von der Beeck, “A comparison of state-
charts variants,” in FTRTFT 94: Formal Tech-
niques in Real-time and Fault-tolerant Sys-
tems, ser. LNCS, W. d. R. Langmaack, H. and
References J. Vytopil, Eds., no. 863. Springer Verlag,
1994.
[1] M. Breen. (2003) On abstraction in finite
state machine models. [Online]. Available:
http://mbreen.com