720 likes | 889 Views
SYSC 3100 System Analysis and Design. UML State Machines . Textbook Reading. As usual, read the relevant textbook section: 12 Read through (some of the material is not covered in the slides)
E N D
SYSC 3100 System Analysis and Design UML State Machines SYSC 3100 System Analysis and Design
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
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
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
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
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
Example for the state of a rental item SYSC 3100 System Analysis and Design
Idle (named) state initial state final state State • Graphically • Special states • Initial state: indicates the default starting state • Final state: indicates that the execution of the state machine has been completed SYSC 3100 System Analysis and Design
Debit balance: Int < 0 Credit balance: Int >= 0 deposit 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 SYSC 3100 System Analysis and Design
checkmate White’s Turn Black wins Start stalemate white moves black moves Draw stalemate Black’s Turn White wins checkmate Informal Example • Chess game SYSC 3100 System Analysis and Design
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
Soda Machine SYSC 3100 System Analysis and Design
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
This event must correspond to an operation in the Campaign class Commissioned authorized(authorizationCode) [contract Signed] /setCampaignActive( ) Active Call Events SYSC 3100 System Analysis and Design
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
No Request Elevator Idle Down Request Up Request Preparing to Move Up Preparing to Move Down Down Request Elevator Started Elevator Started Moving to Floor After(Timeout) Up Request Checking Next Destination Top-Level Statechart for Elevator Control Class SYSC 3100 System Analysis and Design
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) State1 State2 after(60)/action SYSC 3100 System Analysis and Design
Phone Call Statechart SYSC 3100 System Analysis and Design
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 State1 State2 when(condition) SYSC 3100 System Analysis and Design
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
gradeRate() when [rateStartDate <= currentDate] Initial state Lapsed Pending Active Change event when [rateFinishDate <= currentDate] Transition between states after [1 year] Elapsed-time event Final state StatechartExample 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
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
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 Off start [transmission = neutral] Engine On SYSC 3100 System Analysis and Design
no event, no guard • automatic Abstract Example only the event evt1 evt1 State1 State2 evt2[c1] evt2[not c1] [c2] State3 only the guard State4 evt3[not c4 and c3] State5 evt4[c4] evt3[not c4 and not c3] State6 SYSC 3100 System Analysis and Design
State Transition Table SYSC 3100 System Analysis and Design
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
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
/assignManager(); assignStaff() authorized(authorizationCode) [contractSigned] /setCampaignActive() Commissioned Completed Active Paid campaignCompleted() /prepareFinalStatement() paymentReceived(payment) [paymentDue – payment <= zero] paymentReceived(payment) [paymentDue - payment > zero] archiveCampaign() /unassignStaff(); unassignManager() Statechart for the class Campaign Action-expression assigning manager and staff on object creation Transition models any payment event that does not reduce the amount due to zero or beyond Guard condition ensuring complete payment before enteringPaid SYSC 3100 System Analysis and Design
/assignManager(); assignStaff() authorized(authorizationCode) [contractSigned] /setCampaignActive() Active Commissioned Paid Completed campaignCompleted() /prepareFinalStatement() paymentReceived(payment, client) [paymentDue - payment < zero] /client.generateRefund() paymentReceived(payment, client) [paymentDue - payment = zero] paymentReceived(payment, client) [paymentDue – payment > zero] archiveCampaign() /unassignStaff(); unassignManager() A revised statechart for the classCampaign 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
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) StateName entry / entryAction exit/ exitAction SYSC 3100 System Analysis and Design
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
The Order of Action Executions State entry / actionA exit / actionB event1 / actionC event3 / actionE event2 / actionD Sequence of events received event1, event2, event3 Actions executed actionC, actionA, actionB, actionD actionA, actionB, actionE SYSC 3100 System Analysis and Design
StateA entry/A exit/B StateA entry/A exit/B evt1/a1 evt2/a2 evt3/a3 evt1/a1 evt2/a2 Example • Result if sequence evt1,evt3,evt2 is received • a1, A, B, a2 (evt3 is ignored) • a1, A, B, a3, A, B, a2 SYSC 3100 System Analysis and Design
Waiting entry/get(c) GettingToken entry/get(c) GettingBody entry/get(c) Example II Statechart for parsing a simple language such as: ‘<’ string ‘>’ string; [c=‘<‘] [c=‘>‘] / printer.print(token) [c<>‘<‘] [c<>‘>‘] / token.append(c) [c=‘;‘]/printer.print(body) [c<>‘;‘] / body.append(c) SYSC 3100 System Analysis and Design
State entry/ the entry action(s) do/ activity1; activity2 exit/ the exit action(s) 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 SYSC 3100 System Analysis and Design
evt1 evt2 State entry/ A do/ B exit/ C Example Event evt1 is first received and • 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 SYSC 3100 System Analysis and Design
go up (floor) OnFirstFloor MovingUp do/moving to floor arrived go down (floor) go up (floor) MovingDown do/moving to floor Idle entry/timer = 0 do/increase timer arrived when(timer = time-out)/go down (first floor) 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. SYSC 3100 System Analysis and Design
go up (floor) OnFirstFloor arrived go down (floor) go up (floor) Moving do/moving to floor Idle entry/timer = 0 do/increase timer when(timer = time-out)/go down (first floor) Example SYSC 3100 System Analysis and Design
Internal Transitions Event itemSelected() triggers the action highlightItem() Menu Visible state for a DropDownMenuobject Entry action causes the menu to be displayed Menu Visible itemSelected() / highlightItem() entry / displayMenu() exit / hideMenu() do / playSoundClip() Exiting the state triggershideMenu() 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
Top-Level Statechart for ATM Control Class Close Down Insufficient Cash / Eject Entry / Display System Down After ( Elapsed Time) [Closedown Was Requested] Startup Closedown Idle After ( Elapsed Time) Card Inserted / Get PIN [Closedown Not Requested] Entry / Display Welcome Third Invalid, Stolen / Confiscated, Update Status Terminating Processing Customer Input Transaction Cancel / Eject, Display Cancel Rejected / Eject, Display Apology Transfer Selected / Transfer OK / Request Transfer, Display Wait Print Receipt, Update Status Query Selected / Query OK / Request Query, Display Wait Print Receipt, Update Status Processing Transaction Withdrawal Selected / Withdrawal OK / Request Withdrawal, Display Wait Dispense Cash, Update Status SYSC 3100 System Analysis and Design
Textbook Example: Account Class Statechart SYSC 3100 System Analysis and Design
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
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 Active cardInserted Validating Idle [continue] cancel maintain Selecting Processing [not continue] Maintenance entry/ readCard exit/ejectCard Printing SYSC 3100 System Analysis and Design
Active extendCampaign() /modifyBudget() advertsApproved() /authorize() confirmSchedule() Advert Preparation Running Adverts Scheduling campaignCompleted() /prepareFinalStatement() Active 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 The Active state of Campaign showing nested substates SYSC 3100 System Analysis and Design
Textbook Example SYSC 3100 System Analysis and Design
Dispensing Soda Bottle SYSC 3100 System Analysis and Design
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 Maintenance Testing maintain TestingDevices SelfDiagnosis Idle [continue] Commanding Waiting Command [not continue] keyPress SYSC 3100 System Analysis and Design
Example Taking Class Incomplete lab done lab done Lab2 Lab1 project done Term Project Passed completed [pass] Final Test completed [fail] Failed SYSC 3100 System Analysis and Design
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
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