72
SYSC 3100 System Analysis and Design 1 SYSC 3100 System Analysis and Design UML State Machines

SYSC 3100 System Analysis and Design1 UML State Machines

Embed Size (px)

Citation preview

SYSC 3100 System Analysis and Design 1

SYSC 3100 System Analysis and Design

UML State Machines

SYSC 3100 System Analysis and Design 2

Textbook Reading

• As usual, read the relevant textbook section: 12• Read through (some of the material is not covered in the

slides)• Write down questions related to material covered in the

book and ask them at the beginning of class or during office hours

• Look at solved problems and review questions

SYSC 3100 System Analysis and Design 3

Purpose

• Model the behavior of complex entity classes (e.g., customers, accounts) so that their design and verification can be facilitated

• Model the behavior of control classes, which very often have to contain information about the state of execution of the use case (e.g., conditional messages)

• There are systematic ways of implementing classes based on their statechart description

• Sometimes, model the behavior of subsystems or systems, but often too complex

SYSC 3100 System Analysis and Design 4

Statechart

• Statechart: Shows a state machine, i.e., a behaviour that specifies the sequences of states an object goes through during its lifetime in response to events, together with its responses to events.

• Statechart:– Is not concerned with algorithmic behaviour or internal control– Is concerned with “when” operations execute, rather than “what”

operations do, or “how” they are implemented

SYSC 3100 System Analysis and Design 5

Statechart Diagrams (Continued)

• Statechart:– describes the pattern of events, states and state transitions

undergone by objects of a class– describe the life history of instances of a class– typically used to describe «control» objects which handle events

from outside the system (execute use cases)– are not needed for stateless objects which always respond in the

same way to each stimulus, regardless of their state

SYSC 3100 System Analysis and Design 6

State• State: a condition or situation in the life of an object during which it satisfies

some condition, performs some activity (in response to events), or waits for some event.

• The current state of an object is determined by the current value of the object’s attributes (state variables) and the links that it has with other objects

• For example the class StaffMember has an attribute startDate which determines whether a StaffMember object is in the probationary state

• The StaffMember object is in the Probationary state for the first six months of employment. While in this state, a staff member has different employment rights and is not eligible for redundancy pay in the event that they are dismissed by the company.

• Some attributes and links of an object are significant for the determination of its state while others are not.

• staffName and staffNo attributes of a StaffMember object have no impact upon its state

SYSC 3100 System Analysis and Design 7

Example for the state of a rental item

SYSC 3100 System Analysis and Design 8

State

• Graphically

• Special states– Initial state: indicates the default starting state– Final state: indicates that the execution of the state

machine has been completed

Idle

(named) state

initial state final state

SYSC 3100 System Analysis and Design 9

Event

• Event: the occurrence of a stimulus that can trigger a state transition.

• Transition: a relationship between two states indicating that an object in the first state will perform certain actions and enter the second state when a specified event occurs and specified conditions are satisfied.

• State changes caused by events

Debitbalance: Int < 0

Creditbalance: Int >= 0

deposit

SYSC 3100 System Analysis and Design 10

Informal Example

White’sTurn

Black’sTurn

Start

stalemate

stalemate

checkmate

white moves

black moves

checkmateBlack wins

White wins

Draw

• Chess game

SYSC 3100 System Analysis and Design 11

Event

• Event:– a stimulus from one object to another (message)– happen at a point in time, with negligible duration– Also called trigger

• Informal examples:– The door is opened– The piece is moved– The phone received is lifted– The button is pushed

SYSC 3100 System Analysis and Design 12

Soda Machine

SYSC 3100 System Analysis and Design 13

Types of Event

• A change event occurs when a condition becomes true• A call event occurs when an object receives a call to one of

its operations either from another object or from itself• A signal event occurs when an object receives a signal (an

asynchronous communication through a signal object)• An elapsed-time event is caused by the passage of a

designated period of time after a specified event (frequently the entry to the current state)

SYSC 3100 System Analysis and Design 14

Call Events

Commissioned

Active

authorized(authorizationCode) [contract Signed] /setCampaignActive( )

This event must correspond to an operation in the Campaign class

SYSC 3100 System Analysis and Design 15

Signals

• UML: “named event that can be raised”• Signals have properties => modeled as objects, attributes• Typical signal attributes are priority, time sent, sender ID• Passed synchronously or asynchronously between objects• Messages passing a signal object, instance of a «signal»

class. • All the signals in a real-time system are modeled in a class

hierarchy. Signal classes must not be related to “normal” classes.

SYSC 3100 System Analysis and Design 16

Top-Level Statechart for Elevator Control Class                          

ElevatorIdle

Preparing to Move Up

Preparing toMove Down

Moving to Floor

CheckingNext Destination

Up Request

Up Request

Down Request

Down Request

ElevatorStarted

ElevatorStarted

After(Timeout)

No Request

 

SYSC 3100 System Analysis and Design 17

Elapsed-Time / Timeout transition

• A specific kind of event can be used to specify a timeout:

The after(x) event– The UML doesn’t define the units, but commonly they are

milliseconds or microseconds.

• This indicates a timeout event which fires some specified period of time after the state is entered.

• The timeout event is cancelled if :– the source state is exited prior to the timeout. – if another event triggers a transition-to-self (a transition in which

the source and target states are the same)

State1State2after(60)/action

SYSC 3100 System Analysis and Design 18

Phone Call Statechart

SYSC 3100 System Analysis and Design 19

Change Events

• Represent the notification that a condition has become true• Are specified using the “when” keyword• Must have a Boolean expression (e.g., OCL) enclosed in

parentheses designating the condition that must become true in order for the transition to fire

State1State2when(condition)

SYSC 3100 System Analysis and Design 20

Statechart Example

• This example illustrates elapsed-time events and change events• The current state of a GradeRate object can be determined by the two

attributes rateStartDate and rateFinishDate (state variables)• An enumerated state variable may be used to hold the object state, possible

values would be Pending, Active or Lapsed

SYSC 3100 System Analysis and Design 21

StatechartExample

Pending

Active

Lapsed

Transitionbetweenstates

when [rateStartDate <= currentDate]

when [rateFinishDate <= currentDate]

after [1 year]

Final state

Initial state

Changeevent

gradeRate()

Elapsed-timeevent

Statechart for the class GradeRate.

Movement from one state to another is dependent upon events that occur with the passage of time.

SYSC 3100 System Analysis and Design 22

Guard conditions

• Guard condition: a Boolean expression (e.g., OCL where the context object is the object modeled by the statechart) that is evaluated when the transition is triggered by reception of the event trigger.– If the expression evaluates to True, the transition is eligible to fire– If the expression evaluates to False, the transition does not fire and if there

is no other transition that could be triggered by that same event, the event is lost

• Are different from change events: Guard conditions are evaluated when the event fires. Change events fire when a condition becomes true; they are continuously checked when an object changes.

• Syntax:

event(arguments) [guard condition]

SYSC 3100 System Analysis and Design 23

Guard conditions

• Guard condition:– expressed in terms of trigger event parameters, state variables and

operations of the class/object– the value of a condition essentially represents (some aspect of) the

state of the system.– Phone call statechart:

• Incomplete: [self.numberDigits < 7]

Engine OffEngine On

start [transmission = neutral]

SYSC 3100 System Analysis and Design 24

Abstract Example

State1 State2evt1

State3

State4

evt1

evt2[c1]evt2[not c1]

State5

State6

[c2]

evt3[not c4 and c3]

evt3[not c4 and not c3]evt4[c4]

only the event

only theguard

no event,no guard

automatic

SYSC 3100 System Analysis and Design 25

State Transition Table

Statechart in state Condition (if any) Event received Result

State1 evt1 State2evt2

ignoredevt3evt4

State2 evt1 State2

C1 = true evt2 State3C1 = false evt2 State4

evt3ignored

evt4State3 evt1

ignoredevt2evt3evt4

C2 = true State1

SYSC 3100 System Analysis and Design 26

More on State Transitions

• Events that do not trigger any transitions are simply ignored (illegal events)

• An event can trigger no more than one transition • If a transition has no explicit event name, its semantics

depend on whether there is a guard condition (next)– Guard fires when ready to exit the state

and when the guard condition is true– No guard automatic transition when ready

to exit the state

SYSC 3100 System Analysis and Design 27

Actions in Transitions

• Action in a transition:

An executable atomic computation that may directly act on the object that owns the statechart, and indirectly on other objects that are visible to this object

An action may include: operation calls, creation or destruction of another object, assignment, sending of a signal to an object

• Atomicity: cannot be interrupted by an event and therefore runs to completion

• Event syntax:

event(arguments) [guard condition] / action(arguments)

SYSC 3100 System Analysis and Design 28

Statechart for the class Campaign

Commissioned

authorized(authorizationCode)[contractSigned]/setCampaignActive()

/assignManager(); assignStaff()

Active

Completed

Paid

campaignCompleted()/prepareFinalStatement()

paymentReceived(payment)[paymentDue - payment > zero]

paymentReceived(payment)[paymentDue – payment <= zero]

archiveCampaign()/unassignStaff(); unassignManager()

Action-expression assigning manager and staff on object

creation

Guard condition ensuring complete

payment before entering Paid

Transition models any payment event that does not reduce the

amount due to zero or beyond

SYSC 3100 System Analysis and Design 29

A revised statechart for

the class Campaign

Commissioned

authorized(authorizationCode)[contractSigned]/setCampaignActive()

/assignManager(); assignStaff()

Active

Completed

Paid

campaignCompleted()/prepareFinalStatement()

paymentReceived(payment, client)[paymentDue – payment > zero]

paymentReceived(payment, client)[paymentDue - payment = zero]

archiveCampaign()/unassignStaff(); unassignManager()

paymentReceived(payment, client)[paymentDue - payment < zero]/client.generateRefund()

If the user requirements were to change, so that an overpayment is

now to result in the automatic

generation of a refund, a new

transition is added

SYSC 3100 System Analysis and Design 30

Actions in States

A state can have:• An entry action, executed when entering the state• An exit action, executed when exiting the state

This helps:• Dispatching the same action whenever we enter (resp. exit)

a state, no matter which transition led us there (resp. away)

StateNameentry / entryAction

exit / exitAction

SYSC 3100 System Analysis and Design 31

Example: CD Player Playing State

Playing

entry / find start of track, lower head

exit / raise head

Note: Can have sequences of actions associated with entry and exit

SYSC 3100 System Analysis and Design 32

The Order of Action Executions

Stateentry / actionAexit / actionB

event1 / actionC

event2 / actionD

event3 / actionE

Sequence of events receivedevent1, event2, event3

Actions executedactionC, actionA, actionB, actionD actionA, actionB, actionE

SYSC 3100 System Analysis and Design 33

Example

evt1/a1 evt2/a2StateAentry/Aexit/B

Result if sequence evt1,evt3,evt2 is received

• a1, A, B, a2 (evt3 is ignored)

• a1, A, B, a3, A, B, a2

evt3/a3

evt1/a1 evt2/a2StateAentry/Aexit/B

SYSC 3100 System Analysis and Design 34

Example II

Statechart for parsing a simple language such as:

‘<’ string ‘>’ string;

[c<>‘<‘]

[c=‘<‘]

[c<>‘>‘] / token.append(c)

[c<>‘;‘] / body.append(c)

[c=‘;‘]/printer.print(body)

[c=‘>‘] / printer.print(token)

Waitingentry/get(c)

GettingTokenentry/get(c)

GettingBody

entry/get(c)

SYSC 3100 System Analysis and Design 35

State Activity

• State Activity: model an ongoing work in a state.– The object does some work that will begin after the

entry action, continue until it is interrupted by an event, and terminate (if not interrupted) before the exit action.

• A state activity can be interrupted by an event

Stateentry/ the entry action(s)do/ activity1; activity2exit/ the exit action(s)

SYSC 3100 System Analysis and Design 36

Example

Stateentry/ A

do/ Bexit/ C

evt1 evt2

• Event evt2 is received after completion of activity B

A, B, C

• Event evt2 is received before completion of activity B

A, part of B, C

Event evt1 is first received and

SYSC 3100 System Analysis and Design 37

Example

A statechart for an elevator. The elevator starts at the first floor. It can be moving up and down. If the elevator is idle on one floor, a time-out event occurs after a period of time and moves the elevator back to the first floor.

OnFirstFloor

Idleentry/timer = 0

do/increase timer

MovingUpdo/moving to floor

MovingDowndo/moving to floor

go up (floor)

arrivedgo down (floor)

when(timer = time-out)/go down (first floor)

arrived

go up (floor)

SYSC 3100 System Analysis and Design 38

Example

OnFirstFloor

Idleentry/timer = 0

do/increase timer

Movingdo/moving to floor

go up (floor)

arrivedgo down (floor)

when(timer = time-out)/go down (first floor)

go up (floor)

SYSC 3100 System Analysis and Design 39

Internal Transitions

Menu Visible

itemSelected() / highlightItem() entry / displayMenu() exit / hideMenu() do / playSoundClip()

Menu Visible state for a DropDownMenu object

Entry action causes the menu to be displayed

Event itemSelected() triggers the action

highlightItem()

Exiting the state triggers

hideMenu()While the object remains in the Menu Visible

state, the activity causes a sound clip to be played

Note: the state is not exited and entered when internal transitions are Triggered.

SYSC 3100 System Analysis and Design 40

Top-Level Statechart for ATM Control Class

Processing Customer InputTerminatingTransaction

Entry / DisplaySystem Down

Close Down

Entry / DisplayWelcome

Idle

Processing Transaction

ClosedownStartup

Card Inserted / Get PINAfter ( Elapsed Time)

[Closedown Not Requested]

Third Invalid, Stolen / Confiscated, Update Status

Cancel / Eject, Display Cancel

Transfer Selected /Request Transfer, Display Wait

Query Selected /Request Query, Display Wait

Withdrawal Selected /Request Withdrawal, Display Wait

Rejected /Eject, Display Apology

Transfer OK /Print Receipt, Update Status

Query OK /Print Receipt, Update Status

Withdrawal OK /Dispense Cash, Update Status

Insufficient Cash / Eject

After ( Elapsed Time)[Closedown Was Requested]

SYSC 3100 System Analysis and Design 41

Zero balance

Debit

charge(value) / balance = balance + value payment(value)[ value < -balance] / balance = balance + value

Credit

payment(value) / balance = balance + value charge(value)[ value < balance] / balance = balance - value

payment(value)[ value > -balance]/ balance = balance + value

charge(value) [value > balance] /balance = balance - value

charge(value) [value = balance] / balance = 0

payment(value) balance = value

charge(value) / balance= balance - value

open / balance = 0close

payment(value) [value = -balance]/ balance = 0

Textbook Example: Account Class Statechart

SYSC 3100 System Analysis and Design 42

Substates

• A substate is a state that’s nested inside another state– A simple state is a state without any substate– A state with substates is a composite state

• There are two different kinds of substates:– Sequential substates– Concurrent substates

• Common features– Substates must have a default starting substate, and/or several final

(terminating) substates– All substates fulfill the state invariant from their parent state– All substates inherit outgoing transitions from their parent state– But: incoming transitions for parents are not inherited

SYSC 3100 System Analysis and Design 43

Sequential substates

• An object in a composite state can only be in one of that state’s substates at the same time (mutually exclusive)

• Sequential Substates are also called ‘OR‘ states, disjoint substates

Validating

Selecting Processing

Printing

[continue]

[not continue]

entry/ readCardexit/ejectCard

Active

Idle

Maintenance

maintain

cardInserted

cancel

SYSC 3100 System Analysis and Design 44

Active Nested Substates

Advert Preparation

campaignCompleted()/prepareFinalStatement()

Running Adverts SchedulingconfirmSchedule()

extendCampaign()/modifyBudget()

advertsApproved()/authorize()

Active

The Active state of Campaign showing nested substates

The transition from the initial pseudostate symbol should not be labelled with an event but may be labelled with an action, though

it is not required in this example

SYSC 3100 System Analysis and Design 45

Active

addSharer

createJourney

removeSharer

addSharer

FullVacant

Available

addSharer[sharerCount < seats] addSharer[sharerCount = seats]removeSharer

endJourney

endJourney

Textbook Example

SYSC 3100 System Analysis and Design 46

Dispensing Soda Bottle

SYSC 3100 System Analysis and Design 47

Concurrent substates

• If an object can be in a composite state but can also be in more than one of that state’s substates at the same time (may be active simultaneously)

• Concurrent Substates are also called ‘AND‘ states, orthogonal substates

TestingDevices SelfDiagnosis

Waiting Command

[continue]

keyPress

MaintenanceTesting

Commanding

[not continue]

Idle

maintain

SYSC 3100 System Analysis and Design 48

Example

Incomplete

Passed

Failed

Lab1 Lab2

lab done

lab done

TermProject

project done

FinalTest

completed [pass]

completed [fail]

Taking Class

SYSC 3100 System Analysis and Design 49

Concurrent States

• A transition to a complex state is equivalent to a simultaneous transition to the initial states of each concurrent statechart

• An initial state must be specified in both nested state machines in order to avoid ambiguity about which substate should first be entered in each concurrent region

• A transition to the Active state means that the Campaign object simultaneously enters the Advert Preparation and Survey states

SYSC 3100 System Analysis and Design 50

Concurrent States

• Once the composite states is entered a transition may occur within either concurrent region without having any effect on the state in the other concurrent region

• A transition out of the Active state applies to all its substates (no matter how deeply nested)

SYSC 3100 System Analysis and Design 51

The Active State with Concurrent Substates

Advert Preparation

Running Adverts SchedulingconfirmSchedule()

extendCampaign()/modify Budget()

advertsApproved()/authorize()

Active

Survey

Evaluation

surveyComplete()

runSurvey()

Running

Monitoring

campaignCompleted()/prepareFinalStatement()

SYSC 3100 System Analysis and Design 52

Textbook Example

Applicant

Pending payment

Pending legal checks

Member

[ renewal ]

renewalDate

SYSC 3100 System Analysis and Design 53

Dispensing Soda Bottle

SYSC 3100 System Analysis and Design 54

History state

• Unless specified, when a transition enters a composite state, the action of the nested state starts over again at its initial state (unless of course the transition targets a substate directly)

• History state: remembers the last substate that was active prior to leaving the composite state.– Except when the composite state has reached its final

state (if any)

SYSC 3100 System Analysis and Design 55

Example

Collecting

Copying

ClearingUp

Command

BackingUp

evt1

evt2evt3

• In state Command, the statechart receives the sequence evt1, evt2, evt3, evt1

• The sequence of states is Command, Collecting, Copying, Command, Collecting

SYSC 3100 System Analysis and Design 56

Example II

Collecting

Copying

ClearingUp

Command

BackingUp

Hevt1evt2

evt3

• In state Command, the statechart receives the sequence evt1, evt2, evt3, evt1

• The sequence of states is Command, Collecting, Copying, Command, Copying

SYSC 3100 System Analysis and Design 57

Events Triggered

• Transitions are triggered by events (see previous slides)• Transitions can also send signals as specified in the send clauses, specified

after actions and a ‘^’ separator.• Syntax of a transition:

eventReveived(args) [condition] / [target.]action(s), … ^ [target.]signalSent(args), …

A B

C D

evt1/^s2

evt2/^s1

E

SYSC 3100 System Analysis and Design 58

Semantics of Send Clauses

• An object can send a signal to any set of objects which it knows about• May have a designation string (target), e.g., OCL navigation

expression, that that indicates the object or class that will receive the signal

^target.signal(arglist)

• Executed right after the action clauses• Must have a name or identifier string that represents the name of a

signal • May have an argument list (actual parameters) • May refer to parameters of the triggering event and to attributes and

links of the object that owns the statechart

SYSC 3100 System Analysis and Design 59

Sent Signals versus Actions

• Sent clauses result into the asynchronous sending of signals to other objects whereas actions are synchronous

• The “asynchronous” property is the main difference with actions on transitions. Actions on transitions, entry, and exit must be completed before entering the new state. In the send clauses, signals are sent and the resulting operations are executed in an asynchronous manner.

SYSC 3100 System Analysis and Design 60

Substate Example

Partial Dialentry / nb.appendNumber (n)

Startdo / play dial tone

digit(n) [nb is valid]

/ ^dialedNumber(nb)

Dialing

/nb := “ “

digit(n)

Dialing ConnectingIdlelift receiver

dialedNumber(nb)

SYSC 3100 System Analysis and Design 61

Sending Events Between state machines

Off Ontoggle power

toggle power

Off Ontoggle power

toggle power

ControllingTV “TV”

“VCR”Controlling

VCR

powered_up/^television.togglePower

VCR

Remote Control

Television

powered_down/^VCR.togglePower

SYSC 3100 System Analysis and Design 62

Creating and Destroying Objects

• Creating/Destroying an object:– regarded as sending an event to the class itself

• Comments:– the event arguments serve to initialize the object– new objects begin in an initial state from where they receive the

creation event as their first event– a class could have multiple possible “birth” events– an object ceases to exist (is destroyed) when it reaches a top-level

terminal state– as part of this transition it can send an event– the action and event expression can be attached directly to the

terminal state

SYSC 3100 System Analysis and Design 63

Creating and Destroying Objects

State1

• Statechart for class A, who ‘knows’ class B

constructorForA(…)B.create(…)

SYSC 3100 System Analysis and Design 64

Conditional pseudostate

• Conditional pseudostate: a notational shorthand for multiple exiting transitions which share a common source state and triggering event, but each having different guards.– Different exiting transition segments are selected on the basis of

guarding conditions.• The conditional pseudostate isn’t a real state—if the transition isn’t

taken, the triggering event is discarded and the original source state continues to be active.

State1

State2

State3

State4

evt/ action1

[c1]/ action2

[c2]/ action3

[else]/ action4

SYSC 3100 System Analysis and Design 65

Guidelines for Developing state machines

• A state must reflect an identifiable situation or an interval of time when something is happening in the system. A state name is often an adjective (Initial) or a phrase with an adjective (Elevator idle).

• Each state must have a unique name.• It must be possible to exit from every state. It is often the

case that state machines do not have a terminating state. • Do not confuse events and actions. An event cause a state

transition. The action is the effect of a state transition. • Events indicate that something just happened whereas

actions are commands.

SYSC 3100 System Analysis and Design 66

Guidelines for Developing state machines II

• An action executes “instantaneously”. An activity executes throughout a given state.

• You may have more than one action associated with a transition. • All these actions conceptually execute simultaneously; hence no

assumptions can be made about the order in which the actions are executed. Consequently, no interdependencies should exist among the actions or you need to introduce an intermediate state.

• If a state transition is labeled event[condition], a state transition takes place only if, at the moment the event happens, the condition is true.

• Actions, activities, and conditions are optional. Use them only when necessary.

SYSC 3100 System Analysis and Design 67

State Pattern

• Intent: Allow an object to alter its behavior when its internal state changes. The object will appear to change its class.

• Applicability: An object's behavior depends on its state, and it must change its behavior at run-time depending on that state.

• Consequences:– It localizes state-specific behavior and partitions behavior for different states. – It makes the addition of states and transitions easy

• State objects are often Singletons• Like long procedures, large conditional statements are undesirable. They're

monolithic and tend to make the code less explicit, which in turn makes them difficult to modify and extend. The State pattern offers a better way to structure state-specific code.

SYSC 3100 System Analysis and Design 68

Structure

SYSC 3100 System Analysis and Design 69

State Pattern: Example

SYSC 3100 System Analysis and Design 70

State Pattern Deficiencies

• The state pattern does not address UML statechart concepts

• Actions on transitions• Entry and exit actions associated with states• Activities performed while in states• Call events only• The state pattern needs to be expanded

SYSC 3100 System Analysis and Design 71

Example

ConcreteState1

Event/action3

ConcreteState2

Entry/action1Do/activity1Exit/action2

Entry/action4Do/activity2Exit/action5

SYSC 3100 System Analysis and Design 72

Extending the State Pattern

ConcreteState1

enter(context: Context)eventHandler(context: Context)

state = sstate.enter (self)

State

enter(context: Context)eventHandler(context:Context)

Context

setState(s:State)eventHandler()Action1()Action2()Action3()Action4()Action5()Activity1()Activity2()

state

……

state.eventHandler (self)

context..action1()context.activity1()

context..action2()context.action3()context.SetState(nextState)