Chapter 5
Chapter 5
You can best understand a system by first examining its static structure-that is, the sffucture
of its objects and their relationships to each other at a single moment in time (the class mod-
el). Then you should examine changes to the objects and their relationships over time (the
state model). The state model describes the sequences of operations that occur in response
to external stimuli, as opposed to what the operations do, what they operate on, or how they
are implemented.
The state model consists of multiple state diagrams, one for each class with temporal
behavior that is important to an application. The state diagram is a standard computer science
concept (a graphical representation of finite state machines) that relates events and states.
Events represent external stimuli and states represent values of objects. You should master
the material in this chapter before proceeding in the book.
5.1 Events
An eyent is an occurrence at a point in time, such as user depresses lefi button or flight 123
departs from Chicago. Events often correspond to verbs in the past tense Qtower turned on,
alarm set) or to the onset of some condition (paper tray becomes empty, temperature be-
comes lower than freezing). By definition, an event happens instantaneously with regard to
the time scale of an application. Of course, nothing is really instantaneous; an event is simply
an occurrence that an application considers atomic and fleeting. The time at which an event
occurs is an implicit attribute of the event. Temporal phenomena that occur over an interval
of time are properly modeled with a state.
One event may logically precede or follow another, or the two events may be unrelated.
Flight 123 must depart Chicago before it can arrive in San Francisco; the two events are caus-
ally related. Flight 123 may depart before or after flight 456 departs Rome; the two events
are causally unrelated. Two events that are causally unrelated are said tobe concurrent; they
90
5.1 Events 91
have no effect on each other. If the communications delay between two locations exceeds the
difference in event times, then the events must be concurrent because they cannot influence
each other. Even if the physical locations of two events are not distant, we consider the events
concurrent if they do not affect each other. In modeling a system we do not try to establish
an ordering between concurrent events because they can occur in any order.
Events include error conditions as well as normal occurrences. For example, motor
jammed, transaction aborted, andtimeout are typical effor events. There is nothing different
about an error event; only our interpretation makes it an "error."
The term event is often used ambiguously. Sometimes it refers to an instance, at other
times to a class. In practice, this ambiguity is usually not a problem and the precise meaning
is apparent from the context. ffnecessary, you can say event occurrence or event type tobe
precise.
There are several kinds of events. The most coilrmon are the signal event, the change
event, and the time event.
(signalD
"signal, "signal"
FlightDeparture MouseButtonPushed Receiverlifted
airline brtto"
flightNumber location
city
date
Figure 5.2 Change events. A change event is an event that is caused by the
satisfaction of a boolean expression.
Figure 5.3 Time events. A time event is an event caused by the occurrence of
an absolute time or the elapse of a time interval.
5.2 States
A state is an abstraction of the values and links of an object. Sets of values and links are
grouped together into a state according to the gross behavior of objects. For example, the
state of a bank is either solvent or insolvent, depending on whether its assets exceed its lia-
bilities. States often correspond to verbs with a suffix of "ing" (Waiting, Dialing) or the du-
ration of some conditi on (Pow e re d, B e low Fre e zin g).
Figure 5.4 shows the UML notation for a state-a rounded box containing an optional
state name. Our convention is to list the state name in boldface, center the name near the top
of the box, and capitalize the first letter.
5.2 States 93
BelowFreezing
Figure 5.4 States. A state is an abstraction of the values and links of an object.
In defining states, we ignore attributes that do not affect the behavior of the object, and
lump together in a single state all combinations of values and links with the same response
to events. Of course, every attribute has some effect on behavior or it would be meaningless,
but often some attributes do not affect the sequence of control and you can regard them as
simple parameter values within a state. Recall that the purpose of modeling is to focus on
qualities that are relevant to the solution of an application problem and abstract away those
that are irrelevant. The three UML models (class, state, and interaction) present different
views of a system for which the particular choice of attributes and values are not equally im-
portant. For example, except for leading 0s and 1s, the exact digits dialed do not affect the
control of the phone line, so we can summarize them all with state Dialing and track the
phone number as a parametef Sometimes, all possible values of an attribute are iinportant,
but usually only when the number of possible values is small.
The objects in a class have a finite number of possible states----one or possibly some larg-
er number. Each object can only be in one state at a time. Objects may parade through one
or more states during their lifetime. At a given moment of time, the various objects for a class
can exist in a multitude of states.
A state specifies the response of an object to input events. All events are ignored in a
state, except those for which behavior is explicitly prescribed. The response may include the
invocation of behavior or a change of state. For example, if a digit is dialed in state Dial tone,
the phone line drops the dial tone and enters state Dialing; if the receiver is replaced in state
Dial tone, the phone line goes dead and enters state ldle.
There is a certain symmetry between events and states as Figure 5.5 illustrates. Events
represent points in time; states represent intervals of time. A state corresponds to the interval
between two events received by an object. For example, after the receiver is lifted and before
the flrst digit is dialed, the phone line is in state Dial tone. Ttre state of an object depends on
past events, which in most cases are eventually hidden by subsequent events. For example,
events that happened before the phone is hung up do not affect future behavior; the ldle state
"forgets" events received prior to the receipt of the hang up signat.
Figure 5.5 Event vs. state. Events represent points in time; states represent
intervals of time.
Both events and states depend on the level of abstraction. For example, a travel agent
planning an itinerary would treat each segment of a journey as a single event; a flight status
94 Chapter 5 / State Modeling
board in an airport would distinguish departures and arrivals; an air traffic control system
would break each flight into many geographical legs.
You can characterize a state in various ways, as Figure 5.6 shows for the state Alarm
ringing on a watch. The state has a suggestive name and a natural-language description of its
purpose. The event sequence that leads to the state consists of setting the alarm, doing any-
thing that doesn't clear the alarm, and then having the target time occur. A declarative con-
dition for the state is given in terms of parameters, such as current and target time; the alarm
stops ringing after 20 seconds. Finally, a stimulus-response table shows the effect of events
current time and button pushed, including the response that occurs and the next state. The
different descriptions of a state may overlap.
State: AlarmRinging
Description: alarm on watch is ringing to indicate target time
Event sequence that produces the state:
setAlarm (targetTime)
any sequence not including clearAlarm
when (currentTime = targetTime)
Condition that characterizes the state:
alarm = on, alarm setto targetTime, targetTime I currentTime 1
targetTime + 20 seconds, and no button has been pushed since targetTime
Events accepted in the state:
event response next state
when(currentTime = targetnme + 20) resetAlarm normal
bunonPushed (any button) resetAlarm normal
Can links have state? [n as much as they can be considered objects. links can have state.
practical matter, it is generally sufficient to associate state only with objects.
a
An event may cause multiple objects to transition; from a conceptual point of view such tran-
sitions occur concurrently.
A guard condition is a boolean expression that must be true in order for a transition to
occur. For example, ataffic light at an intersection may change only if a road has cars wait-
ing. A guarded transition fires when its event occurs, but only if the guard condition is true.
For example, "when you go out in the morning (event), if the temperature is below freezing
(condition), then put on your gloves (next state)." A guard condition is checked only once-,
at the time the event occurs, and the fransition fires if the condition is true. If the condition
becomes true later, the transition does not then flre. Note that a guard condition is different
from a change event-a guard condition is checked only once while a change event is, in ef-
fect, checked continuously.
Figure 5.7 shows guarded transitions for traffic lights at an intersection. One pair of elec-
tric eyes checks the north-south left turn lanes; another pair checks the east-west turn lanes.
lf no car is in the north-south and/or east-west turn lanes, then the traffic light confrol logic
is smart enough to skip the left turn portion of the cycle.
The UML notation for a transition is a line from the origin state to the target state. An
arrowhead points to the target state. The line may consist of several line segments. An event
may label the transition and be followed by an optional guard condition in square brackets.
By convention, we usually confine line segments to a rectilinear grid. We italicize the event
name and show the condition in normal font.
state diagrams by direct interpretation or by converting the semantics into equivalent pro'
gramming code.
T\e state model consists of multiple state diagrams, one state diagram for each class
with important temporal behavior. The state diagrams must match on their interfaces-
events and guard conditions. The individual state diagrams interact by passing events and
through the side effects of guard conditions. Some events and guard conditions appear in a
single state diagram; others appear in multiple state diagrams for the purpose of coordina-
tion. This chapter covers only individual state diagrams; Chapter 6 discusses state models of
interacting diagrams.
A class with more than one state has important temporal behavior. Similarly, a class is
temporally important if it has a single state with multiple responses to events. You can rep-
resent state diagrams with a single state in a simple nongraphical form-a stimulus-response
table listing events and guard conditions and the ensuing behavior.
PhoneLine
calledPhoneAnswers
calledPhoneHangsUp
Figure 5.8 state diagram for a telephone line. A state diagram specifies
the state sequences caused by evefit sequences.
One-shot state diagrams represent objects with finite lives and have
initihl and final
states' The initial state is.entered on creation ofan object; entry ofthe
final state implies de-
struction of the object. Figure 5.9 shows a simplifled life cycle tf a chess game
with a default
initial state (solid circle) and a default final state (bull.s eye).
As an alternate notation, you can indicate initial and dnal states via entry
and exit points.
I1 Figure 5.10 the start entry point leads to white's first turn, and the chess game
eventually
ends with one of three possible outcomes. Entry points (hollow
circles) and exit points (cir-
cles enclosing an "x") appear on the state diagram's perimeter
and may be named.
98 Chapter 5 / State Modeling
Figure 5.9 State diagram for chess game. One-shot diagrams represent
objects with finite lives.
Black wins
Draw
White wins
Figure 5.10 State diagram for chess game. You can also show one-shot
diagrams by using entry and exit points.
State. Drawn as a rounded box containing an optional name. A special notation is avail-
able for initial states (a solid circle) and finat states (a bull's-eye or encircled "x").
5.5 State Diagram Behavior 99
f Transition. Drawn as a line from the origin state to the target state. An arrowhead points
to the target state. The line may consist of several line segments.
I Event. A signal event is shown as a label on a transition and may be followed by paren-
thesized attributes. A change event is shown with the keyword whenfollowed by a pa-
renthesized boolean expression. A time event is shown with the keyw ordwhen folhowed,
by a parenthesized expression involving time or the keyword after followed by a paren-
thesized expression that evaluates to a time duration.
I State diagram. Enclosed in arectangular frame with the diagram name in a small pen-
tagonal tag in the upper left corner.
I Guard condition. Optionally listed in square brackets after an event.
I Effects (to be explained in next section). Can be attached to a fiansition or state and are
listed after a slash (7). Multiple effects are separated with a comma and are performed
concurrently. (You can create intervening states if you want multiple effects to be per-
formed in sequence.)
We also recommend some style conventions. We list the state name in boldface with the first
letter capitalized. We ital:lcize event names with the initial letter in lower case. Guard condi-
tions and effects are in normal font and also have the initial letter in lower case. We try to
confine transition line segments to a rectilinear grid.
Figure 5.12 Activities for pop-up menu. An activity is behavior that can be
.executed in resPonse to an event.
5.5.2 Do-Actiuities
A ilo-activity is an activity that continues for an extended time. By definition, a do-activity
can only occur within a state and cannot be attached to a transition. For example, the warning
light may flash during the Paper jam state for a copy machine (Figure 5.13). Do-activities
include continuous operations, such as displaying a picture on a television screen, as well as
sequential operations that terminate by themselves after an interval of time, such as closing
a valve.
Paper jam
do / flash warning light
The notation "d.o /' denotes a do-activity that may be performed for all or part of the
duration that an object is in a state. A do-activity may be intemrpted by an event that is re-
ceived during its execution; such an event may or may not cause a transition out of the state
containing the do-activity. For example, a robot moving a part may encounter resistance,
causing it to cease moving.
depress / motor up
door open / motor off
depress / motor up
Figure 5.15 shows the same model using activities on entry to states. An entry activity
is shown inside the state box following the keyword entry and,ao'|" character.Whenever the
state is entered, by any incoming transition, the entry activity is performed. An entry activity
is equivalent to attaching the activity to every incoming transition. [f an incoming transition
already has an activity, its activity is performed first.
Exit activities are less conunon than enffy activities, but they are occasionally useful. An
exit activity is shown inside the state box following the keyword exit'and a "f' character.
Whenever the, state is exited, by any outgoing transition, the exit activity is performed first.
If a state has multiple activities, they are performed in the following order: activities on
the incoming transition, entry activities, do-activities, exit activities, activities on the outgo-
ing transition. Events that cause transitions out of the state can interrupt do-activities. If a do-
activity is intemrpted, the exit activity is still performed.
In general, any event can occur within a state and cause an activity to be performed. En-
try and exit are only two examples of events that can occur. As Figure 5.16 shows, there is a
diffeience between an event within a state and a self-transition; only the self-transition caus-
es the entry and exit activities to be executed.
102 Chapter 5 / State Modeling
Closed
shutdown / motor ofl
Figure 5.16 Event within a state vs. self-transition. A self-transition causes enffy
and exit activities to be executed. An event within a state does not.
5.5.5 *ndingSignats
An object can perform the activity of sending a signal to another object. A system of objects
interacts by exchanging signals.
The activity "send target.s(attributes)" sends signal S with the given attributes to the
target object or objects. For example, the phone line sends a connect(phone number) signal
to the switcher when a complete phone number has been dialed. A signal can be directed at
a set of objects or a single object. If the target is a set of objects, each of them receives a sep-
arate copy of the signal concurrently, and each of them independently processes the signal
and determines whether to flre a transition. If the signal is always directed to the same object,
the diagram can omit the target (but it must be supplied eventually in an implementation, of
course).
Ifan object can receive signals from more than one object, the order in which concurrent
signals are received may affect the final state; this is called a race condition. For example,
in Figure 5.15 the door may or may not remain open if the button is pressed at about the time
the door becomes fully open. A race condition is not necessarily a design error, but concur-
5.6 Practical Tips 103
rent systems frequently contain unwanted race conditions that must be avoided by careful
design. A requirement of two signals being received simultaneously is never a meaningful
condition in the real world, as slight variations in transmission speed are inherent in any dis-
tributed system.
Phonel-ine
calledPhoneAnswers / connectline
calledPhoneHangsUp / disconnectline
Figure 5.17 State diagram for phone line with activities. State diagrams let
you express what objects do in response to events.
There are several kinds of events, such as a signal event, a change event, and a time
event. A signal event is the sending or receipt of information communicated among objects.
A change event is an event that is caused by the satisfaction of a boolean expression. A time
event is an event caused by the occurrence of an absolute time or the elapse of a relative time.