Overview - IBM€¦ · Overview The state machine view describes the dynamic behavior of objects...

13
81 M L U 7 State Machine View Overview The state machine view describes the dynamic behavior of objects over time by modeling the lifecycles of objects of each class. Each object is treated as an isolated entity that communicates with the rest of the world by detecting events and re- sponding to them. Events represent the kinds of changes that an object can detect—the receipt of calls or explicit signals from one object to another, a change in certain values, or the passage of time. Anything that can affect an object can be characterized as an event. Real-world happenings are modeled as signals from the outside world to the system. A state is a set of object values for a given class that have the same qualitative re- sponse to events that occur. In other words, all objects with the same state react in the same general way to an event, so all objects in a given state execute the same effect—an action or activity—when they receive the same event. Objects in dif- ferent states, however, may react differently to the same event, by performing different effects. A state machine describes a small number of states that an object may hold. For each state, the state machine specifies the consequences of receiving each kind of event as an effect and a change to a new state. For example, an auto- matic teller machine reacts to the cancel button one way when it is processing a transaction and another way when it is idle. State machines describe the behavior of classes, but they also describe the dynamic behavior of use cases, collaborations, and methods. For one of these ob- jects, a state represents a step in its execution. We talk mostly in terms of classes and objects in describing state machines, but they can be applied to other elements in a straightforward way. State Machine A state machine is a graph of states and transitions. Usually a state machine is at- tached to a class and describes the response of an instance of the class to events refbook.book Page 81 Monday, June 14, 2004 10:34 AM

Transcript of Overview - IBM€¦ · Overview The state machine view describes the dynamic behavior of objects...

81

MLU7

State Machine View

Overview

The state machine view describes the dynamic behavior of objects over time bymodeling the lifecycles of objects of each class. Each object is treated as an isolatedentity that communicates with the rest of the world by detecting events and re-sponding to them. Events represent the kinds of changes that an object candetect—the receipt of calls or explicit signals from one object to another, a changein certain values, or the passage of time. Anything that can affect an object can becharacterized as an event. Real-world happenings are modeled as signals from theoutside world to the system.

A state is a set of object values for a given class that have the same qualitative re-sponse to events that occur. In other words, all objects with the same state react inthe same general way to an event, so all objects in a given state execute the sameeffect—an action or activity—when they receive the same event. Objects in dif-ferent states, however, may react differently to the same event, by performingdifferent effects. A state machine describes a small number of states that an objectmay hold. For each state, the state machine specifies the consequences of receivingeach kind of event as an effect and a change to a new state. For example, an auto-matic teller machine reacts to the cancel button one way when it is processing atransaction and another way when it is idle.

State machines describe the behavior of classes, but they also describe thedynamic behavior of use cases, collaborations, and methods. For one of these ob-jects, a state represents a step in its execution. We talk mostly in terms of classesand objects in describing state machines, but they can be applied to other elementsin a straightforward way.

State Machine

A state machine is a graph of states and transitions. Usually a state machine is at-tached to a class and describes the response of an instance of the class to events

refbook.book Page 81 Monday, June 14, 2004 10:34 AM

82 Part 2 • UML Concepts

that it receives. State machines may also be attached to behaviors, use cases, andcollaborations to describe their execution.

A state machine is a model of all possible life histories of an object of a class. Theobject is examined in isolation. Any external influence from the rest of the world issummarized as an event. When the object detects an event, it responds in a waythat depends on its current state. The response may include the execution of an ef-fect and a change to a new state. State machines can be structured to share transi-tions, and they can model concurrency.

A state machine is a localized view of an object, a view that separates it from therest of the world and examines its behavior in isolation. It is a reductionist view ofa system. This is a good way to specify behavior precisely, but often it is not a goodway to understand the overall operation of a system. For a better idea of thesystem-wide effects of behavior, interaction views are often more useful. State ma-chines are useful for understanding control mechanisms, however, such as user in-terfaces and device controllers.

Event

An event is a type of noteworthy occurrence that has a location in time and space.It occurs at a point in time; it does not have duration. Model something as anevent if its occurrence has consequences. When we use the word event by itself, weusually mean an event descriptor—that is, a description of all the individual eventoccurrences that have the same general form, just as the word class means all theindividual objects that have the same structure. A specific occurrence of an event iscalled an occurrence. Events may have parameters that characterize each individ-ual event occurrence, just as classes have attributes that characterize each object.Events can be divided into various explicit and implicit kinds: signal events, callevents, change events, and time events. Table 7-1 is a list of event types and theirdescriptions.

Table 7-1: Kinds of Events

Event Type Description Syntax

call event Receipt of an explicit synchronous call request by an object

op (a:T)

change event A change in value of a Boolean expression when (exp)

signal event Receipt of an explicit, named, asynchro-nous communication among objects

sname (a:T)

time event The arrival of an absolute time or the pas-sage of a relative amount of time

after (time)

refbook.book Page 82 Monday, June 14, 2004 10:34 AM

Chapter 7 • State Machine View 83

Signal. A signal is kind of classifier that is explicitly intended as a communicationvehicle between two objects; the reception of a signal is an event for the receivingobject. The sending object explicitly creates and initializes a signal instance andsends it to one or a set of explicit objects. Signals embody asynchronous one-waycommunication, the most fundamental kind. The sender does not wait for the re-ceiver to deal with the signal but continues with its own work independently. Tomodel two-way communication, multiple signals can be used, at least one in eachdirection. The sender and the receiver can be the same object.

Signals may be declared in class diagrams as classifiers, using the keyword«signal»; the parameters of the signal are declared as attributes. As classifiers, sig-nals can have generalization relationships. Signals may be children of other signals;they inherit the attributes of their parents, and they trigger transitions that containthe parent signal type (Figure 7-1).

Figure 7-1. Signal hierarchy

UserInputdevice

Mouse

location

ButtonKeyboardCharacter

character

InputEvent

time

Control Graphic

PunctuationAlphanumericSpace

Mouse MouseButtonDown

ButtonUp

«signal»

«signal»

«signal» «signal»

«signal» «signal» «signal»

«signal» «signal»

«signal»

«signal»

Character Character

abstract signal

concrete signals

refbook.book Page 83 Monday, June 14, 2004 10:34 AM

84 Part 2 • UML Concepts

Call event. A call event is the reception of a call of an operation by an object. Thereceiving class chooses whether an operation will be implemented as a method ora call event trigger in a state machine (or possibly both). The parameters of the op-eration are the parameters of the call event. Once the receiving object processes thecall event by taking a transition triggered by the event or failing to take any transi-tion, control returns to the calling object. Unlike a method, however, a state ma-chine transition triggered by a call event may continue its own execution inparallel with the caller.

Change event. A change event is the satisfaction of a Boolean expression that de-pends on designated attribute values. This is a declarative way to wait until a con-dition is satisfied, but it must be used with care, because it represents a continuousand potentially nonlocal computation (action at a distance, because the value orvalues tested may be distant). This is both good and bad. It is good because it fo-cuses the model on the true dependency—an effect that occurs when a given con-dition is satisfied—rather than on the mechanics of testing the condition. It is badbecause it obscures the cause-and-effect relationship between the action thatchanges an underlying value and the eventual effect. The cost of testing a changeevent is potentially large, because in principle it is continuous. In practice, how-ever, there are optimizations that avoid unnecessary computation. Change eventsshould be used only when a more explicit form of communication is unnatural.

Note the difference between a guard condition and a change event. A guard con-dition is evaluated once when the trigger event on the transition occurs and the re-ceiver handles the event. If it is false, the transition does not fire and the conditionis not reevaluated. A change event is evaluated continuously until it becomes true,at which time the transition fires.

Time event. Time events represent the passage of time. A time event can be speci-fied either in absolute mode (time of day) or relative mode (time elapsed since agiven event). In a high-level model, time events can be thought of as events fromthe universe; in an implementation model, they are caused by signals from somespecific object, either the operating system or an object in the application.

State

A state machine defines a small number of named states. A state can be character-ized in three complementary ways: as a set of object values that are qualitativelysimilar in some respect; as a period of time during which an object waits for someevent or events to occur; or as a period of time during which an object performssome ongoing do activity. A state may have a name, although often it is anony-mous and is described simply by its effects and relationships. In effects, states arethe units of control from which state machines are constructed.

refbook.book Page 84 Monday, June 14, 2004 10:34 AM

Chapter 7 • State Machine View 85

In a state machine, a set of states is connected by transitions. A transition con-nects two states (or more, if there is a fork or join of control). A transition is pro-cessed by the state that it leaves. When an object is in a state, it is sensitive to thetrigger events on transitions leaving the state.

A state is shown as a rectangle with rounded corners (Figure 7-2).

Transition

A transition leaving a state defines the response of an object in the state to the oc-currence of an event. In general, a transition has an event trigger, a guard condi-tion, an effect, and a target state. Table 7-2 shows kinds of transitions and impliciteffects invoked by transitions.

Figure 7-2. State

Table 7-2: Kinds of Transitions and Implicit Effects

Transition Kind Description Syntax

entry transition The specification of an entry activity that is executed when a state is entered

entry/ activity

exit transition The specification of an exit activity that is executed when a state is exited

exit/ activity

external transition A response to an event that causes a change of state or a self-transition, together with a specified effect. It may also cause the execution of exit and/or entry activities for states that are exited or entered.

e(a:T )[guard]/activity

internal transition A response to an event that causes the execution of an effect but does not cause a change of state or execution of exit or entry activities

e(a:T )[guard]/activity

Confirm Credit

refbook.book Page 85 Monday, June 14, 2004 10:34 AM

86 Part 2 • UML Concepts

External transition. An external transition is a transition that changes the activestate. This is the most common kind of transition. It is drawn as an arrow from thesource state to the target state, with other properties shown as a text string at-tached to the arrow (Figure 7-3).

Trigger event. The trigger specifies the event that enables a transition. The eventmay have parameters, which are available to an effect specified as part of the tran-sition. If a signal has descendants, receipt of any descendant of the signal enablesthe transition. For example, if a transition has signal MouseButton as a trigger (seeFigure 7-1), then receipt of MouseButtonDown will trigger the transition.

An event is not a continuous thing; it occurs at a point in time. When an objectreceives an event occurrence, the event occurrence is placed into an event pool forthe object. An object handles one event occurrence at a time. When the object isfree, an event occurrence is removed from the pool. A transition must fire at thetime the object handles the event; the event occurrence is not “remembered” untillater (except in the special case of deferred events, which remain in the event pooluntil they trigger a transition or until the object enters a state where they are nolonger deferred). If two events occur simultaneously, they are handled one at atime. An event occurrence that does not trigger any transition is simply ignoredand lost. This is not an error. It is much easier to ignore unwanted events than totry to specify all of them.

Figure 7-3. External transitions

Confirm Credit Process Order

Cancel Order

approved/debit account()

rejected

Waiting

receive order[amount > $25]

receive order[amount < $25]

action

guard condition

trigger event

transition

trigger event

transition

transition

transition

refbook.book Page 86 Monday, June 14, 2004 10:34 AM

Chapter 7 • State Machine View 87

Guard condition. A transition may have a guard condition, which is a Boolean ex-pression. It may reference attributes of the object that owns the state machine, aswell as parameters of the trigger event. The guard condition is evaluated when thetrigger event occurs. If the expression evaluates as true, then the transition fires—that is, its effects occur. If the expression evaluates as false, then the transition doesnot fire. The guard condition is evaluated only once, at the time the trigger eventoccurs. If the condition is false and later becomes true, it is too late to fire the tran-sition.

The same event can be a trigger for more than one transition leaving a singlestate. Each transition with the same event must have a different guard condition. Ifthe event occurs, a transition triggered by the event may fire if its condition is true.Often, the set of guard conditions covers all possibilities so that the occurrence ofthe event is guaranteed to fire some transition. If all possibilities are not coveredand no transition is enabled, then an event is simply ignored. Only one transitionmay fire (within one thread of control) in response to one event occurrence. If anevent enables more than one transition, only one of them fires. A transition on anested state takes precedence over a transition on one of its enclosing states. If twoconflicting transitions are enabled at the same time, one of them fires nondeter-ministically. The choice may be random or it may depend on implementation de-tails, but the modeler should not count on a predicable result.

If an orthogonal state is active, each region in it is active, meaning that multiplestates (at least one in each region) may be active concurrently. If multiple states areactive, a single event occurrence may trigger a transition in each orthogonal re-gion. The concurrent transitions are executed concurrently and do not interact,except possibly indirectly because of effects on shared objects.

Completion transition. A transition that lacks an explicit trigger event is triggeredby the completion of activity in the state that it leaves (this is a completion transi-tion). A completion transition may have a guard condition, which is evaluated atthe time the activity in the state completes (and not thereafter). Completion tran-sitions take priority over ordinary events and do not wait for a normal run-to-completion step.

Effect. When a transition fires, its effect (if any) is executed. An effect may be anaction or an activity. An action is a primitive computation, such as an assignmentstatement or simple arithmetic computation. Other actions include sending a sig-nal to another object, calling an operation, creating or destroying an object, andgetting and setting attribute values. An effect may also be an activity—that is, a listof simpler actions or activities. An action or activity cannot be terminated oraffected by simultaneous effects. (An advanced profile might add an action thatterminates or interrupts other activities.) Conceptually, one activity is processed at

refbook.book Page 87 Monday, June 14, 2004 10:34 AM

88 Part 2 • UML Concepts

a time; therefore, a second event cannot be handled during the execution of an ef-fect.

The overall system can perform multiple activities simultaneously. An imple-mentation system can process hardware interrupts and time share between severalactions. An activity is noninterruptible within its own thread of control. Oncestarted, it must complete and it must not interact with other simultaneously activeeffects. This is called run-to-completion semantics. But effects should not be usedas a long transaction mechanism. Their duration should be brief compared to theresponse time needed for external events. Otherwise, the system might be unableto respond in a timely manner.

An effect may use parameters of the trigger event and attributes of the owningobject as part of its expression.

Change of state. When the execution of the effect is complete, the target state of thetransition becomes active. This may trigger an exit activity or an entry activity (orseveral if the state machine traverses several nested states from the source to thetarget state).

Nested states. States may be nested inside other composite states (see following en-try). A transition leaving an outer state is applicable to all states nested within it.The transition is eligible to fire whenever any nested state is active. If the transitionfires, the target state of the transition becomes active. Composite states are usefulfor expressing exception and error conditions, because transitions on them applyto all nested states without the need for each nested state to handle the exceptionexplicitly.

Entry and exit activities. A transition across one or more levels of nesting may exitand enter states. A state may specify activities that are performed whenever thestate is entered or exited. Entering the target state executes an entry activity at-tached to the state. If the transition leaves the original state, then its exit activity isexecuted before the effect on the transition and the entry activity on the new state.

Entry activities are often used to perform setup needed within a state. Becausean entry activity cannot be evaded, any actions that occur inside the state can as-sume that the setup has occurred, regardless of how the state is entered. Similarly,an exit activity is an activity that occurs whenever the state is exited, an opportu-nity to perform clean up. It is particularly useful when there are high-level transi-tions that represent error conditions that abort nested states. The exit activity canclean up such cases so that the state of the object remains consistent. Entry andexit activities could in principle be attached to incoming and outgoing transitions,but declaring them as special effects of the state permits the state to be defined in-dependently of its transitions and therefore encapsulated.

refbook.book Page 88 Monday, June 14, 2004 10:34 AM

Chapter 7 • State Machine View 89

Internal transition. An internal transition has a source state but no target state.The firing rules for an internal transition are the same as for a transition thatchanges state. An internal transition has no target state, so the active state does notchange as a result of its firing. If an internal transition has an effect, the effect is ex-ecuted, but no change of state occurs, and therefore no exit or entry activities areexecuted. Internal transitions are useful for modeling interrupt situations that donot change the state (such as counting occurrences of an event or putting up a helpscreen).

Entry and exit activities use the same notation as internal transitions, exceptthey use the reserved words entry and exit in place of the event trigger name, al-though these effects are triggered by external transitions that enter or leave thestate.

A self-transition invokes exit and entry activities on its state (conceptually, it ex-its and then reenters the state); therefore, it is not equivalent to an internal transi-tion. Figure 7-4 shows entry and exit activities as well as internal transitions.

Composite State

A simple state has no substructure, just a set of transitions and possible entry andexit activities. A composite state is one that has been decomposed into regions,each of which contains one or more direct substates. Table 7-3 lists the variouskinds of states.

A decomposition of a nonorthogonal state into direct substates is similar to spe-cialization of a class. An outer state is decomposed into several inner states, each ofwhich inherits the transitions of the outer state. Only one direct substate per non-orthogonal state can be active at one time. The outer state represents the conditionof being in any one of the inner states.

Transitions into or out of a composite state invoke any entry activity or exit ac-tivity of the state. If there are several composite states, a transition across severallevels may invoke multiple entry activities (outermost first) or several exit activi-ties (innermost first). If there is an effect on the transition itself, the effect is exe-cuted after any exit activities and before any entry activities are executed.

Figure 7-4. Internal transitions, and entry and exit actions

Enter Password

entry / set echo to star; reset passwordexit / set echo to normaldigit / handle characterclear / reset passwordhelp / display help

entry and exit activities

internal transitions

state name

refbook.book Page 89 Monday, June 14, 2004 10:34 AM

90 Part 2 • UML Concepts

Table 7-3: Kinds of States

State Kind Description Notation

simple state A state with no substructure

orthogonal state A state that is divided into two or more regions. One direct substate from each region is concurrently active when the composite state is active.

nonorthogonal state

A composite state that contains one or more direct substates, exactly one of which is active at one time when the composite state is active

initial state A pseudostate that indicates the starting state when the enclosing state is invoked

final state A special state whose activation indi-cates the enclosing state has com-pleted activity

terminate A special state whose activation ter-minates execution of the object own-ing the state machine

junction A pseudostate that chains transition segments into a single run-to-completion transition

choice A pseudostate that performs a dynamic branch within a single run-to-completion transition

history state A pseudostate whose activation restores the previously active state within a composite state

S

S

S

H

refbook.book Page 90 Monday, June 14, 2004 10:34 AM

Chapter 7 • State Machine View 91

Each region of a composite state may have an initial state. A transition to thecomposite state boundary is implicitly a transition to the initial state. A new objectstarts at the initial state of its outermost state. Similarly, a composite state can havea final state. A transition to the final state triggers a completion transition on thecomposite state. If an object reaches the final state of its outermost state, it is de-stroyed. Initial states, final states, entry activities, and exit activities permit the def-inition of a state to be encapsulated independent of transitions to and from it.

Figure 7-5 shows a sequential decomposition of a state, including an initialstate. This is the control for a ticket-selling machine.

A decomposition of an orthogonal state into orthogonal regions represents in-dependent computation. When an orthogonal state is entered, the number of con-trol threads increases as a direct substate in each orthogonal region becomesactive. When the orthogonal state is exited, the number of control threads de-creases. Often, concurrency is implemented by a distinct object for each substate,but orthogonal states can also represent logical concurrency within a single object.Figure 7-6 shows the concurrent decomposition of taking a university class.

It is often convenient to reuse a fragment of a state machine in other state ma-chines. A state machine can be given a name and referenced from a state of one ormore other machines. The target state machine is a submachine, and the state ref-erencing it is called a submachine state. It implies the (conceptual) substitution ofa copy of the referenced state machine at the place of reference, a kind of state ma-chine subroutine. A submachine can define named entry points and exit pointsthat connect to internal states. Transitions to a submachine state can use connec-tion points that reference these entry and exit points, hiding the internal structure

submachine state A state that references a state machine definition, which conceptu-ally replaces the submachine state

entry point A externally visible pseudostate within a state machine that identifies an internal state as a target

exit point A externally visible pseudostate within a state machine that identifies an internal state as a source

Table 7-3: Kinds of States

State Kind Description Notation

s: M

Ta

U b

refbook.book Page 91 Monday, June 14, 2004 10:34 AM

92 Part 2 • UML Concepts

of the submachine from external clients. Instead of a submachine, a state can con-tain an do activity—that is, a computation or continuous activity that takes timeto complete and that may be interrupted by events. Figure 7-7 shows a subma-chine reference.

A transition to a submachine state causes activation of the initial state of thetarget submachine. To enter a submachine at other states, an entry point can bereferenced. A entry point identifies a state in the submachine without exposing thecontents of the submachine.

Figure 7-5. State machine

identifyUser: Identify

Idle

Selecting

Confirming

Selling

fail

push “buy”push “resume”

push “confirm”

insert card

push “cancel”

Purchasing

exit / eject card

pick (seat) / add to selection (seat)

entry / sell ()

initial state

final state

completiontransition

outer transitionaborts internalactivity

submachine reference

normal exit

explicitexit

/reset selection activity

entryactivity

internaltransition

event

completiontransition

refbook.book Page 92 Monday, June 14, 2004 10:34 AM

Chapter 7 • State Machine View 93

Figure 7-6. State machine with orthogonal composite state

Figure 7-7. Submachine state

Lab1 Lab2

Term

lab done

project done

Incomplete

Project

Final pass

Test

fail

lab done

Taking Class

orthogonal state

explicit exit

normalcompletiontransition

final state ofone region

orthogonal

state machine

initial state

failed

region

final state(default exit)

exit point

(default entry)

Help

entry / display help screenexit / remove help screen

quit

query / show answer

help: Help

help command

run: Run

run command

submachine state

submachine

This submachine can be used many times.

submachine state

main machine

CommandWait

refbook.book Page 93 Monday, June 14, 2004 10:34 AM