Object-Oriented Analysis and Design Session 3b: Behavioral Modeling – State machine diagrams Mira Balaban & Arnon Sturm
Outline Introduction to State Machine.……………..……... 3 State Machine Diagrams Syntax and Semantics….11 State Hierarchy………………………………...….31 State History Mechanism ………………...……....41 State Concurrency ……………………….……….46 Concluding Example ……………………………..57 State Machine Diagrams and UML ……..……….62 Summary ……………………………………...….65 Mira Balaban & Arnon Sturm
Introduction to State Machine Mira Balaban & Arnon Sturm
Characterization of reactive systems Continuous interaction with the environment inputs and outputs are asynchronous in time. Respond to interrupts. Stringent time requirements. Multiple possible scenarios of operation, depending on the history of previous behavior. Based on interacting processes that operate in parallel. Mira Balaban & Arnon Sturm
Automata A machine whose output behavior is not only a direct consequence of the current input, but also of some past history of its inputs. Characterized by an internal state which represents this past experience. OFF ON Mira Balaban & Arnon Sturm
What are Statecharts? Statecharts are visual formalism for specifying behavior of complex systems. Developed by David Harel. Employee rest[break] Working Resting Mira Balaban & Arnon Sturm
State Machine (Automaton) Diagram Graphical rendering of automata behavior on Lamp On off on off Lamp Off Mira Balaban & Arnon Sturm
Outputs and Actions As the automaton changes state it can generate outputs: on off Lamp On Lamp Off on/print(”on”) Mealy automaton on off Lamp On print(”on”) Lamp Off Moore automaton Mira Balaban & Arnon Sturm
Extended State Machines (1) Addition of variables (“extended state”) off on Lamp On Lamp Off on/ctr := ctr + 1 ctr : Integer Mira Balaban & Arnon Sturm
Extended State Machines (2) An extended (Mealy) state machine is defined by: a set of input signals (input alphabet) a set of output signals (output alphabet) a set of states a set of transitions triggering signal action a set of extended state variables an initial state designation a set of final states (if terminating automaton) Mira Balaban & Arnon Sturm
State Machine Diagrams Syntax and Semantics Mira Balaban & Arnon Sturm
State Machine Diagram Ready stop /ctr := 0 Done stop “top” state State Initial pseudostate top Trigger Ready Transition stop /ctr := 0 Done Final state Action stop Mira Balaban & Arnon Sturm
Statechart Diagram Elements States Any component or object within the system can be at a specific state in a given time. When holding the state, an object (or a component) can perform activities (which can be interrupted). Transitions Specification of rules for moving between states. A transition may consist of a trigger, condition, and an action. Mira Balaban & Arnon Sturm
Initial and Final States start White’s turn checkmate Black wins stalemate black moves white moves Draw stalemate Black’s turn White wins checkmate Mira Balaban & Arnon Sturm
Activity and Action An activity: An action: can be performed within a state. can be continuous. can be sequential. takes time. An action: can be performed within a state or during a transition. can not be interrupted. is atomic. can take time. Mira Balaban & Arnon Sturm
Event-Driven Behavior Event = a type of observable occurrence interactions: object operation invocation (call event). asynchronous signal reception (signal event). occurrence of time instants (time event) interval expiry. calendar/clock time. change in value of some entity (change event). Event Instance = an instance of an event (type) occurs at a particular time instant and has no duration. Mira Balaban & Arnon Sturm
Transitions A transition is enabled if the object is at a state preceding the transition. An enabled transition is activated upon its trigger activation. An initial transition indicates that the default is entering S2. A transition can connect the same state. S3 S1 S2 E1 E2 Mira Balaban & Arnon Sturm
Object Behavior - General Model Simple server model: Initialize Object Handling depends on specific request type Wait for Request void:offHook (); {busy = true; obj.reqDialtone(); … }; Handle Request Terminate Object Mira Balaban & Arnon Sturm
Object Behavior and State Machines Direct mapping: on off Lamp On Lamp Off on/print(”on”) stop Handle Event Initialize Object Terminate Object Wait for Event Mira Balaban & Arnon Sturm
State Entry and Exit Actions LampOn e2 entry/lamp.on(); exit/lamp.off(); e1 Mira Balaban & Arnon Sturm
Order of Actions: Simple Case Entry actions are performed after (entering) transition actions. Exit actions are performed before (exiting) transition actions. off/printf(“to off”); LampOff entry/lamp.off(); exit/printf(“exiting”); LampOn entry/lamp.on(); off/printf(“needless”); Resulting action sequence: printf(“exiting”); printf(“to off”); lamp.off(); printf(“exiting”); printf(“needless”); lamp.off(); Mira Balaban & Arnon Sturm
exit/printf(“exiting”); Internal Transitions Self-transitions that bypass entry and exit. actions Internal transition triggered by an “off” event LampOff entry/lamp.off(); exit/printf(“exiting”); off/null; Mira Balaban & Arnon Sturm
State (“Do”) Activities Forks a concurrent thread that executes until: the action completes or the state is exited. “do” activity Error entry/printf(“error!”) do/while (true) alarm.ring(); Mira Balaban & Arnon Sturm
Guards Conditional execution of transitions side-effect free Selling bid [value < 100] /reject Selling Happy bid [value >= 200] /sell Unhappy bid [(value >= 100) & (value < 200)] /sell Mira Balaban & Arnon Sturm
Guards and Events (1) S1 S2 E1 S3 Entered C S1 S2 E1 S3 [C] Mira Balaban & Arnon Sturm
Guards and Events (2) Special operators in(a) – means in state a. en(b) – means the occurrence of entering state b. ex(c) – means the occurrence of exiting state c. tm(min) – means trigger if min time units have passed. Mira Balaban & Arnon Sturm
on hook / disconnect line Phone Line Example Idle Dialing off hook digit (n) valid number Ringing routed Connected called phone answers / connect line Disconnected called phone hangs up / disconnect line Time out time out invalid number on hook busy message done Dial tone do: sound dial tone Connecting do: find connection Recorded message do: play message Busy tone do: sound busy tone on hook / disconnect line Mira Balaban & Arnon Sturm
Static Conditional Branching Merely a graphical shortcut for convenient rendering of decision trees. Selling Unhappy Happy bid [value >= 200] /sell [value < 100] /reject [(value >= 100) & (value < 200)] /sell Mira Balaban & Arnon Sturm
Dynamic Conditional Branching Choice pseudostate: guards are evaluated only when the decision point is reached. Selling Unhappy Happy bid /gain := calculatePotentialGain(value) [gain >= 200] /sell [gain < 100] /reject [(gain >= 100) & (gain < 200)] /sell Dynamic choicepoint Mira Balaban & Arnon Sturm
State Hierarchy Mira Balaban & Arnon Sturm
States Hierarchy (1) Intended to cluster together alternative states of a single aspect / object. Results: OR states. An OR state is a super-state of its sub-states. A state that has no sub-states is a basic state. The states in an IndentationStatus statechart: Mira Balaban & Arnon Sturm
States Hierarchy (2) States hierarchy is used for describing different levels of abstraction. High Level Detailed Level Mira Balaban & Arnon Sturm
States Hierarchy (3) States hierarchy is used for clustering. Un clustered clustered Mira Balaban & Arnon Sturm
States Hierarchy (4) Initial States– one per state. To be in a state is to be in ONE of its sub states. Mira Balaban & Arnon Sturm
States Hierarchy (5) Graduated attack on complexity states decomposed into state machines off/ LampOff entry/lamp.off() LampOn entry/lamp.on() on/ LampFlashing flash/ 1sec/ FlashOff entry/lamp.off() FlashOn entry/lamp.on() on/ Mira Balaban & Arnon Sturm
the initial pseudostate States Hierarchy (6) Default transition to the initial pseudostate Higher-level transitions off/ LampOff entry/lamp.off() LampOn entry/lamp.on() on/ LampFlashing flash/ 1sec/ FlashOff entry/lamp.off() FlashOn entry/lamp.on() on/ Mira Balaban & Arnon Sturm
transition (no trigger) States Hierarchy (7) Triggered by a completion event generated automatically when an immediately nested state machine terminates. completion transition (no trigger) Committing Phase1 Phase2 CommitDone Mira Balaban & Arnon Sturm
States Hierarchy (8) Two or more transitions may have the same triggered event inner transition takes precedence. if no transition is triggered, event is discarded. LampFlashing FlashOn on/ off/ Mira Balaban & Arnon Sturm FlashOff
Actions execution sequence: States Hierarchy (9) Same approach as for the simple case S1 exit/exS1 S2 entry/enS2 initS2 E/actE S11 exit/exS11 S21 entry/enS21 Actions execution sequence: exS11 exS1 actEenS2 initS2 enS21 Mira Balaban & Arnon Sturm
State History Mechanism Mira Balaban & Arnon Sturm
History Mechanism (1) Mira Balaban & Arnon Sturm
History Mechanism (2) Mira Balaban & Arnon Sturm
History Mechanism (3) G Mira Balaban & Arnon Sturm
History Mechanism (4) Return to a previously visited hierarchical state deep and shallow history options Diagnosing suspend/ Diagnostic1 Diagnostic2 Step11 Step12 Step21 Step22 resume/ H* Mira Balaban & Arnon Sturm
State Concurrency Mira Balaban & Arnon Sturm
Orthogonality and Concurrency (1) Multiple simultaneous perspectives on the same entity Child Adult Retiree age Staff Member Manager employee Mira Balaban & Arnon Sturm
Orthogonality and Concurrency (2) Describe independent components of a behavior. Behavior of parts of an aggregate object. Enforce synchronization of concurrent activities. Concurrency is an AND-decomposition of a state. To be in a state S is to be in ALL of its components. S is an AND state. Mira Balaban & Arnon Sturm
Orthogonality and Concurrency (3) Combine multiple simultaneous descriptions Child Adult Retiree age Staff Member Manager employee Staff Member Manager employee Child Adult Retiree age Mira Balaban & Arnon Sturm
Orthogonality and Concurrency (4) B C E G F A D a b g d m (in G) Use of Orthogonal Regions C,F C,E C,G B,G B,E B,F a b g d m No Use of Orthogonal Regions
Orthogonality and Concurrency (5) All mutually orthogonal regions detect the same events and respond to them “simultaneously”. Outlaw LawAbiding Poor Rich financialStatus legalStatus robBank/ Mira Balaban & Arnon Sturm
Orthogonality and Concurrency (6) Typically through shared variables or awareness of other regions’ state changes. sane : Boolean flying : Boolean Catch22 sanityStatus flightStatus (flying)/ Crazy entry/sane := false; Sane entry/sane := true; request Grounding/ Flying entry/flying := true; Grounded entry/flying := false; (sane)/ (~sane)/ Mira Balaban & Arnon Sturm
Transition Sequence A transition might be a trigger An event can trigger additional transitions Several transition can be triggered within a single step Solution The number of triggered transition should be limited A C b/d a/c d/a c/b B D
Transition Forks and Joins For transitions into/out of orthogonal regions: Staff Member employee Child Adult Retiree age Manager Mira Balaban & Arnon Sturm
Reducing Multiple Transitions (1) Mira Balaban & Arnon Sturm
Reducing Multiple Transitions (2) Mira Balaban & Arnon Sturm
Concluding Example Mira Balaban & Arnon Sturm
Mini Organ Example (1) Mira Balaban & Arnon Sturm
Mini Organ Example (2) The button a is used for switch the organ on and off The organ enables a song selection and its style. When the organ is turned on the display shows the mode: STYLE or SONG and its number. The default is song #1/sytle #1 and the mode is STYLE. To select a style one need to press the b button and the required style number (1-9). Each style has a function that return its name – StyleName(x). To select a song one need to press the c button and the required song number(1-9). Each song has a function that return its name – SongName(x). Pressing the start button plays the current song following the current style. Another press stop the music. It is possible to change the song or style during music playing. Mira Balaban & Arnon Sturm
Mini Organ Example (3) a - pressing the a button Events a - pressing the a button b - pressing the b button c - pressing the c button s - pressing the START button i - pressing the a digit button (2-9) 1 - pressing the 1 button songend – end of song playing Variables i,j – can get values between 2-9 k,m – can get values between 1-9 w – can get a song or style name Mira Balaban & Arnon Sturm
Mini Organ Example (4) c b x y Mira Balaban & Arnon Sturm
State Machine and UML Mira Balaban & Arnon Sturm
Dishwasher – Class Diagram Tank evTankDrain() evTankFill() Dishwasher cycles : int rinseTime : int washTime : int dryTime : int Dishwasher() setup() evStart() evOpen() evClose() evQuick() evNormal() evIntensive() evService() Jet evJetOff() evJetSpray() evJetPulse() Heater evHeaterOff() evHeaterOn() itsTank 1 itsJet itsHeater Mira Balaban & Arnon Sturm
Dishwasher – State Machine Diagram AcmeHeater AcmeJet off on evHeaterOn evHeaterOff running pulsing spraying idle evJetPulse evJetOff evJetSpray Dishwasher AcmeTank draining filling full> empty> tm(4000)/ itsDishwasher->GEN(evFull); evTankFill itsDishwasher->GEN(evEmpty); evTankDrain Mira Balaban & Arnon Sturm
Summary UML uses a variant of Harel’s statecharts adjusted to software modeling needs Used to model event-driven (reactive) behavior well-suited to the server model inherent in the object paradigm Includes a number of sophisticated features that realize common state-machine usage patterns: entry/exit actions state activities dynamic and static conditional branching Also, provides hierarchical modeling for dealing with very complex systems hierarchical states hierarchical transitions orthogonality Mira Balaban & Arnon Sturm