SEN2022 · Week 10 · Behavioral Modeling

Behavioral modeling 2: state machine and activity diagrams

The states of an object over its lifetime (state, event, guard, action) and the flow of a process (action, decision, merge, fork, join, swimlane). The exam brings 'draw the state machine for X' or 'activity diagram with swimlanes'.

behavioral state machinestateeventtransitionguard conditionactionactivityinitial statefinal statecomposite stateactivity diagramaction nodecontrol flowobject flowdecision nodemerge nodefork nodejoin nodeswimlane (partition)object node

On the first page you saw how objects exchange messages with each other. On this page there are two different views. The state machine diagram shows the states a single object goes through during its life: a book copy on the shelf, set aside, on loan, overdue, lost. The activity diagram shows the steps, decisions and parallel tasks of a process: how a food order flows from the customer to the kitchen and from the kitchen to the courier. On the exam both come as “draw” questions; marks come from the details: the transition label pattern, the difference between fork and decision, swimlanes.

Golden rules:

  1. A state machine is for an object, an activity diagram is for a process.
  2. Transition label: event [guard] / action. All three are optional but the order is fixed.
  3. Diamond = choose one path (decision/merge). Thick bar = all in parallel (fork/join).
  4. Swimlane = responsibility. Every action must be in the right lane.

The state machine diagram

Elements

ElementNotationMeaning
StateRounded rectangleA condition of the object, in which it stays for some time
Initial stateSmall filled circleThe starting point
Final stateFilled circle inside a ringThe end of the object’s life
TransitionArrowMoving from one state to another
EventAbove the arrowThe occurrence that triggers the transition
Guard[condition]If true, the transition happens
Action/ operation()Instantaneous work during the transition
Activitydo / ... inside the stateOngoing work while in the state

Three kinds of line can be written inside a state: entry / ... (on entering), do / ... (while in the state), exit / ... (on leaving).

Kinds of event: call event (an operation call: pickUp()), time event (after 48h), change event (when dueDate < today), signal event (an external signal).

Worked example: Copy (a book copy)

Scenario: “When a new copy is added to the catalog it is available. If a student reserves it, it is set aside for 48 hours; if the student comes and picks it up it is lent out, and if not it becomes available again. An available copy can also be lent directly. If the return date passes, the copy is considered overdue. When returned, it becomes available; if it is overdue, a fine is charged on return. A copy that is 30 days overdue is considered lost and is removed from the catalog.”

Step 1: States. Available, On Hold, On Loan, Overdue, Lost.

Step 2: Transitions.

SourceEvent [guard] / actionTarget
●addToCatalogAvailable
Availablereserve / startHoldTimer()On Hold
AvailablecheckOut / setDueDate()On Loan
On HoldpickUp / setDueDate()On Loan
On Holdafter 48h (holdExpired)Available
On LoanreturnAvailable
On Loanwhen today > dueDateOverdue
Overduereturn / chargeFine()Available
Overdueafter 30 days / markLost()Lost
LostremoveFromCatalog◉

Step 3: The drawing.

 ●
 | addToCatalog
 v
+-----------+  reserve /         +---------+
| Available |  startHoldTimer()  | On Hold |
|           |------------------->|         |
|           |<-------------------|         |
+-----------+   after 48h        +---------+
  ^  ^  |                           |
  |  |  | checkOut /               | pickUp /
  |  |  | setDueDate()             | setDueDate()
  |  |  v                           v
  |  | +---------+<-----------------+
  |  +-| On Loan |
  |    +---------+
  | return  | when today > dueDate
  |         v
  |    +---------+  after 30 days  +------+
  +----| Overdue |---------------->| Lost |
return/+---------+  / markLost()   +------+
chargeFine()                          |
                    removeFromCatalog v ◉

Count: 5 states, 10 transitions (including the initial and final arrows).

PITFALL · confusing a state with an action. “Charge a fine” is not a state, it is an action (/ chargeFine() on the transition). A state is a condition the object stays in for a while, and it usually expresses an adjective or a condition: Available, Overdue.

The activity diagram

An activity diagram shows a business process or the flow of a use case. It resembles a flowchart but adds parallelism (fork/join) and responsibility (swimlane). In the textbook’s framework it is also part of functional modeling; it is used to visualize the inside of use cases.

Elements

ElementNotationMeaning
ActionRounded rectangleA single step (“Place Order”)
ActivityRounded rectangle, with a sub-flowWork made of several steps
Control flowSolid arrowOrder
Object nodeRectangleA flowing object: Order [paid]
Object flowArrow (to/from an object)The flow of data
Initial nodeFilled circleStart
Activity finalFilled circle inside a ringEnds the whole flow
Flow finalCircle with an XEnds only that branch
DecisionDiamond, [guard] on the outputsChoose one path
MergeDiamond, several inputsJoin alternative paths
ForkThick bar, one input many outputsStart in parallel
JoinThick bar, many inputs one outputWait for all
SwimlaneStripThe responsible role

Worked example: a food order (with swimlanes)

Scenario: “The customer places an order and pays. If the payment is declined, they try another card. The restaurant evaluates the order; if it rejects, the customer is notified and the process ends. If it accepts, while the food is being prepared a courier is assigned at the same time. When both are done, the courier picks up the order and delivers it; the customer confirms the delivery.”

 Customer      | Restaurant     | Courier
---------------+----------------+-------------
 ●             |                |
 |             |                |
 [Place Order] |                |
 |             |                |
 [Pay]<----+   |                |
 |         |   |                |
 <dec>-----+   |                |
 |  [declined] |                |
 | [paid]      |                |
 +------------>[Review Order]   |
               |   |            |
 [Get notice]<-+--<dec>         |
 |  [rejected] |   | [accepted] |
 ◉             |   |            |
               | ==+== (fork)   |
               | |       |      |
               |[Prepare]+----->[Assign
               | Food]   |      | Courier]
               | |       |      |  |
               | ======= (join)<---+
               |    |           |
               |    +---------->[Pick Up]
               |                |  |
               |                [Deliver]
 [Confirm      |                |  |
  Receipt]<----+----------------+--+
 |             |                |
 ◉             |                |

Reading:

  • 3 swimlanes: Customer, Restaurant, Courier.
  • 2 decisions: the payment result ([paid] / [declined]) and the restaurant’s decision ([accepted] / [rejected]).
  • 1 fork, 1 join: Prepare Food and Assign Courier are in parallel; Pick Up waits for both to finish.
  • 2 activity finals: the rejected order and the normal end.

TIP · a merge after a decision. If the paths split by a decision will come together again, use a merge diamond. In the payment loop, the declined path returns to “Pay”; it is neater if this return is drawn with a merge before Pay.

PITFALL · decision instead of fork. The words “at the same time” in “while the food is being prepared a courier is assigned at the same time” mean fork. If you use a decision, only one of the two happens.

Which diagram when?

QuestionDiagram
Which objects exchange messages, in what order?Sequence
Which objects are connected, who talks to whom?Communication
Which states does an object go through during its life?State machine
What steps, decisions and parallel tasks does a process consist of; who does them?Activity (with swimlanes)

Common mistakes

Wrong ideaThe truth
A state machine is for a processIt is for the life cycle of an object
Label order action [guard] eventevent [guard] / action
A state machine for every classOnly for those with a complex life cycle
A state name is a verb (“Lend”)A state expresses a condition (“On Loan”); verbs are events or actions
Fork = decisionFork starts in parallel, decision chooses one
Merge waits for all branchesJoin waits; merge does not wait
Showing responsibility without swimlanesUse swimlanes to show who does it
Activity final and flow final are the sameActivity final ends everything, flow final ends a single branch

Test yourself

Exam-style questions. Solve them on paper first, then reveal the answer.

Question 1easy

On a state machine transition labeled returnBook [daysLate > 0] / chargeFine(), identify the event, guard and action.

Show answer
Event: returnBook; guard: daysLate > 0; action: chargeFine()

The transition label pattern: event [guard] / action. The event triggers the transition, the transition happens if the guard is true, and the action is the instantaneous work done during the transition.

Question 2easy

Which kind of class deserves a state machine diagram?

  1. Every class
  2. A class whose objects go through clearly different states with different behavior
  3. Only abstract classes
  4. Only controller classes
Show answer
B) A class whose objects go through clearly different states with different behavior

A state machine is drawn only for classes with a complex life cycle: Order, Copy, Reservation, Membership. Objects that behave differently depending on their state (for example, one that cannot be lent while "On Loan") are candidates. Classes like Address do not need one.

Question 3medium

In the Copy state machine on this page, how many states (excluding initial and final pseudo-states) are there?

Show answer
5

Available, On Hold, On Loan, Overdue, Lost. The starting point (filled circle) and the end (circle with a ring) are not counted as states. Total 5 states.

Question 4medium

In the same Copy state machine, which event moves a copy from On Hold back to Available without a loan?

Show answer
holdExpired (48 hours pass without pickup)

When the reservation period expires (a temporal event, 'after 48h'), the copy becomes Available again. If the student comes and takes it (pickUp), it becomes On Loan.

Question 5hard

Food-delivery Order: states Placed, Accepted, Preparing, OutForDelivery, Delivered, Cancelled. The customer may cancel only before the restaurant starts preparing. From which states is there a 'cancel' transition?

Show answer
From Placed and from Accepted

There is no cancellation once preparation has started (Preparing and later). From the Placed and Accepted states, a transition to the Cancelled state is drawn with the 'cancel' event. If you like, you can also show this with a single arrow from a composite state ('Cancellable') containing Placed and Accepted.

Question 6medium

In an activity diagram, what is the difference between a decision node and a fork node?

Show answer
A decision (diamond) chooses ONE outgoing path based on guards; a fork (thick bar) starts ALL outgoing paths in parallel.

Decision: a diamond, with [guard] on the outgoing arrows, only one is chosen; it is joined back with a merge. Fork: a thick bar, all branches start at the same time; a join waits for all of them to finish.

Question 7easy

Which node waits until ALL incoming parallel flows have finished?

  1. Merge
  2. Join
  3. Decision
  4. Final
Show answer
B) Join

A join (thick bar) continues when all the incoming parallel flows have completed. A merge (diamond) continues when one of the alternative paths arrives, without waiting.

Question 8easy

What do swimlanes show in an activity diagram?

Show answer
Who (which actor, role or department) is responsible for each action.

Swimlanes (partitions) divide the diagram into vertical or horizontal strips; each strip is an actor or a unit. The role whose strip an action is in performs it. Handoffs of responsibility become visible.

Question 9medium

In the food-delivery activity diagram on this page, how many swimlanes and how many fork bars are there?

Show answer
3 swimlanes, 1 fork (and 1 join)

The lanes: Customer, Restaurant, Courier. When the Restaurant accepts the order there is a fork: 'Prepare Food' and 'Assign Courier' start in parallel; when both finish, the join passes control to 'Pick Up Order'.

Question 10hard

Write the transition for: 'When a membership expires, if the member has auto-renew on, charge the card.' (from Active)

Show answer
expire [autoRenew = true] / chargeCard() : Active → Active (or → Renewed)

Event: expire. Guard: [autoRenew = true]. Action: chargeCard(). Depending on the model, the target is again Active (a self-transition) or a separate Renewed state. The other branch: expire [autoRenew = false] → Expired.

Question 11hard

What is the difference between an action and an activity in a state machine?

Show answer
An action is atomic and instantaneous (on a transition or entry/exit); an activity takes time and runs while the object is in a state (do/).

An action is uninterruptible and instantaneous: / chargeFine() on a transition, entry / startTimer() inside a state. An activity is ongoing work, written inside a state as do / trackLocation(), and it is interrupted when the state is left.

Verification: Conceptual and drawing/counting questions were checked against the rules of the UML 2 state machine (transition label event [guard] / action) and the activity diagram (decision/merge diamonds, fork/join thick bars, swimlanes). The numbers of states, transitions and nodes in the diagrams on the page were counted by hand and compared twice.

Review card

State machine: the states of ONE object over its lifetime State: rounded rectangle; initial ● ; final ◉ Transition label: event [guard] / action Event: occurrence (call, time "after 48h", change "when x") Guard: [true/false], the transition happens if true Action: instantaneous (on a transition, entry/, exit/); Activity: ongoing (do/) Composite state: substates inside Draw only for classes with a complex life cycle Activity: process flow (workflow or use case flow) Decision/merge: diamond, ONE path; Fork/join: thick bar, ALL in parallel Swimlane: who does it Object node: rectangle, flowing data (Order[paid]) Activity final ◉ ends everything; flow final ⊗ a single flow