Dynamic Modeling Grady Booch, James Rumbaugh, and Ivar Jacobson, The Unified Modeling Language User Guide, 2nd edition, Addison Wesley, 2005. Outline • Dynamic models • State machine diagrams (a.k.a. statechart) – Modeling object or system states • Interaction diagrams – Sequence diagrams (a.k.a. message sequence) • The time order of interactions between objects – Communication diagrams (a.k.a. collaboration) • Messages passed between objects 2 Dynamic Models • Used to model control aspects (e.g., when) • Several different models possible, e.g., – Focusing on state changes – Focusing on interactions 3 Dynamic Models • Used to model control aspects (e.g., when) • Several different models possible, e.g., – Focusing on state changes • • • • Used to show software control Sequence of operations and events Transitions between states UML state machine diagrams – Focusing on interactions 4 Dynamic Models • Used to model control aspects (e.g., when) • Several different models possible, e.g., – Focusing on state changes – Focusing on interactions • Used to show dynamic relationships between objects • Messages, interfaces, and timings • UML interaction diagrams – Sequence diagrams, focusing on ordered interactions – Communication diagrams, focusing on interaction links – Timing diagrams, focusing on interaction timings 5 Outline Dynamic models • State machine diagrams • Interaction diagrams 6 Modeling State Changes • Modeling object/system states – UML state machine diagram – Depicts the flow of control using states and transitions by describing • How an object or system changes over time • Event (e.g., operation calls) it may respond to • How it respond to them – Generalization of finite state machines 7 Modeling Object States • Network of states and transitions • One diagram for each object with important dynamic behavior • Independent timing of state machines for different objects (asynchronous) switch pushed On Off switch pushed 8 Elements of State Machine Diagrams Final State Initial State Transition Running Idle State 9 Initial and Final States White’s turn checkmate Black win stalemate start black moved white moved Black’s turn Draw stalemate checkmate White win 10 States • Some phase during the lifetime of an object that is significant of its behavior (e.g., observable or different behavior) • Condition or situation in the life of a system (or object) during which it: – Satisfies some condition (i.e., state invariant), – Performs some activity, or – Waits for some events. • Set of values of properties that affect the behavior of the system (or object). – Determines response to an event – Thus, different states may produce different responses to the same event 11 States (Cont.) • All objects have states. • A state is an abstraction of the values maintained by the object that determine behavior. • Examples: – – – – – The invoice is paid. The car is parked. The engine is running. Kate is working. Jim is playing. 12 State Corresponds to Interval of Time between Events • Events: points in time • State: interval of time; may correspond to a continuous activity – E.g., waiting, ringing, and flying • State may be associated with value of object satisfying some condition. – E.g., automobile transmission is in reverse. – E.g., balance of account is negative 13 Identifying States • Ignore attributes that don't affect behavior • Combine set of attributes that form a parameter of the control – E.g., the control is not changed by changing the digits in the phone call. 14 Specifying States • Name (optional) • Internal activities (optional) – Actions and activities performed while in the state – Predefined: entry, exit, do • Internal transitions (optional) – Reaction within a state but without changing state Name Internal activities Internal transitions Brewing do / brew coffee pot removed/ suspend pot replaced/ resume 15 Internal Activities and Transitions • Actions and activities performed while in the state – Action: atomic – Activity: more complex behavior • Action/activity label, specifying triggering conditions – Entry: performed on entry to state – Exit: performed on exit from state – Do: performed while in the state Attacking entry/unsheathe sword do/charge exit/sheathe sword enemy swings[distance<3 ft]/dodge • Internal transitions – Reactions to events that doesn’t cause state changes (see transitions) 16 Example [number.isValid()] Starting entry / start dial tone exit / end dial tone dialed (n) Dialing entry / number.append(n) dialed (n) 17 Events • Something that happens at a point in time – No duration: instantaneous – At least we think of it this way when we model (abstraction) • Stimulus from one object to another • May result in a change of state • May result in event being sent to another object 18 Two Events: • May be unrelated (concurrent) – E.g., flight 123 departs El Paso and flight 555 departs Las Vegas. • May depend on each other (sequential) – E.g., flight 123 departs El Paso and flight 123 arrives Las Vegas. 19 Transitions • Relationship between two states indicating that a system (or object) in the first state will: – Perform certain actions and – Enter the second state when specified event occurs and specified condition is satisfied. • Consists of: – Source and target states – Optional event trigger, guard condition, and action trigger [guard] / action Source Target 20 Transitions (Cont.) • Source state – State affected by transition • Event trigger Source – Triggering the transition • Guard condition – Boolean evaluated after the event trigger. Transition only occurs if guard is true trigger [guard] / action • Action – Atomic operation that occurs as the transition occurs Target • Target state – State active after transition 21 Example trigger [guard] / action Source Target keyPressed(key) [key == ENTER_KEY] / str := inputBuffer Note that every transition should be labeled. 22 Transitions (Cont.) • Lead from one state to another • Instantaneous • Several types of events: – – – – A condition becomes true. An explicit signal is received from an object. An operation is called by an object. A designated period of time passes. 23 Phone Example digit dialed (n) [incomplete] connected Connecting Dialing digit dialed (n) [invalid] Ringing digit dialed (n) [valid] / connect busy Busy Invalid 24 Protocol vs. Behavior Machines • Protocol state machine – Specifies the intended pattern of calls on an object by specifying • which operations of the object can be called in which state • and under which condition, thus specifying the allowed call sequences on the object's operations. – Describes an object's life cycle. – Post-conditions are used instead of actions • Behavior state machine – Expresses the behavior of part of a system, e.g., to define object and operation behavior – Actions are used instead of post-conditions – States can have actions (entry, exit, do) 25 Protocol State Machine credit(x) Not Overdrawn [balance >= 0] debit(x)[balance - x < 0] credit(x)[balance + x >= 0] debit(x)[balance - x >= 0] Overdrawn [balance < 0] credit(x)[balance + x >= 0] 26 Protocol State Machine Account credit(x) -balance: Integer + balance(): Integer + credit(x:Integer): void + debit(x:Integer): void Not Overdrawn [balance >= 0] debit(x)[balance - x < 0] credit(x)[balance + x >= 0] debit(x)[balance - x >= 0] Overdrawn [balance < 0] credit(x)[balance + x >= 0] 27 In Class: Digital Watch • (Pairs) Draw a state machine diagram The watch has a single mode button and a single advance button. Pressing the mode button once and then pressing the advance button increments the hours by 1. Each press of the advance button increments the hour. Pressing the mode button the second time allows advancing the minutes by one. Pressing the mode button a third time displays the current time. While displaying the current time, the advance button is ignored. Pressing the mode button allows the user to set the hour again. 28 In Class: Toy Train (Pairs) Draw a state machine diagram Initially, headlight is off, and train is not moving. If power on, headlight shines, and train moves forward. If power off, headlight goes out, but train still moves forward. If power on, headlight comes on, and train does not move. If power off, headlight goes off, and train stays stopped. If power on, headlight comes on, and train moves backward. If power off, headlight goes off, but train still moves backward. If power on, headlight comes on, and train doesn’t move. If power off, headlight off, and train remains stopped. Repeats from step 2 above. 29 Structuring State Machine Diagrams Can this diagram be presented better? recovery success recovery failure Normal anomaly Recovery Identification pressure problem recovery success recovery success Pressure Recovery temperature problem recovery Unstructured!failure Temperature Recovery recovery failure 30 Better Presented: anomaly Recovery Recovery Identification Normal recovery success recovery failure pressure problem Pressure Recovery temperature problem Temperature Recovery 31 Composite States (Cont.) • • • • • • States containing one or more state diagrams Used to simplify diagrams Inside, looks like state machine diagrams May have composite transitions May have transitions from substates May have "history states" (H symbol) denoting the most recently occupied state • Sequential (OR) and parallel (AND) states 32 Composite States and Transitions Transition to/from composite state Active Idle Validating Selecting Maintenance Processing H Transition to history state Printing Transition from substate 33 Example of Composite State 34 Including Composite States Dialing Number Include / Dialing Dialing [number.isValid()] Starting entry / start dial tone exit / end dial tone dialed(n) Partial Dialing entry / number.append(n) dialedn) 35 Sequential (OR) and Parallel (AND) States • States can be divided into concurrent parts, called “regions”. • OR state: composite state with single region • AND state: composite state with multiple regions – System is in all regions of the state, i.e., executes concurrently. 36 Example of AND State 37 Synchronization • Concurrency (split of control) • Synchronization Superstate substate1 substate2 substate3 substate4 38 Example Composite state Fork Maintaining Idle Testing Testing Diagnose Join Commanding Waiting Command Concurrent regions 39 Another Example Incomplete HW1 HW2 Passed Project Midterm Final fail Failed 40 Example of Synchronization Play Remote Control On Off On Off Stop On Play On/Stop Off Stop Off MP3 Player On/Play Off/Stop 41 In Class: Avoiding Combinatorial Explosion of States (Pairs) A car can be in the state of moving or stop. It can also be clean or dirty. Model the states of a car: • without using parallel states • using parallel states What will happen if we add a third property (say, Red vs. Blue) and a fourth property (say, Enclosed vs. Convertible)? 42 In Class: Toy Train (Pairs) Draw a state machine diagram Initially, headlight is off, and train is not moving. If power on, headlight shines, and train moves forward. If power off, headlight goes out, but train still moves forward. If power on, headlight comes on, and train does not move. If power off, headlight goes off, and train stays stopped. If power on, headlight comes on, and train moves backward. If power off, headlight goes off, but train still moves backward. If power on, headlight comes on, and train doesn’t move. If power off, headlight off, and train remains stopped. Repeats from step 2 above. 43 In Class: Office Phone • (Pairs) Draw a state machine diagram describing the operation of an office phone. Assume that the phone has keys for the digits 09, #, and *. It can detect when the receiver is onhook or off-hook. The phone is idle when the receiver is on-hook. Model phone calls. – making calls (e.g., dialing, connecting, talking), – receiving calls (e.g., ringing, talking) 44 Outline Dynamic models State machine diagrams • Interaction diagrams 45 Modeling Interactions • Focus on communications among elements – Ordering of interactions – Messages and interfaces – Communication links – Timings of messages (between when message sent and received) 46 UML Interaction Diagrams • Whole class of diagrams including – Sequence Diagrams • The time order of interactions between objects – Communication Diagrams • Messages passed between objects – Interaction Overview Diagram • Overview diagram that hides much of the detail – Timing Diagram • Interactions with precise time axis (for real-time or timesensitive systems) 47 Sequence Diagrams • Depicts object interaction by highlighting the time ordering of method invocations • Describes a sequence of method calls among objects • (This is the only interaction diagram we’ll look at.) 48 Example sdPlaceOrder : Customer : Or der : Payment : Product : Supplier object place an or der control pr ocess lifetime validate if ( payment ok ) deliver if ( not in stock ) back order g et addres s mail to address message 49 Example (Cont.) : Customer : Order : Payment : Product : Supplier place an order process validate Sequence of message sending if ( payment ok ) deliver if ( not in stock ) back order g et addres s mail to address 50 Different Types of Messages Synchronous message Asynchronous message Return message <<create>> <<destroy>> o: Class Creation message Destruction message 51 Return Messages sdPlaceOrder :CustomerWIndow Change :Customer Update Return (dashed line, open arrow) 52 Creation and Destruction sdPlaceOrder :CustomerWIndow Change <<create>> :Customer getRating() <<destroy>> 53 In Class: Weblog Content Management System (CMS) • (Pairs) Draw a sequence diagram for creating a new blog account. The content management system allows an administrator to create a new blog account, provided the personal details of the new blogger are verified using the author credential database. A summary of the new blog account’s details should be mailed to the author. 54