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'.
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:
- A state machine is for an object, an activity diagram is for a process.
- Transition label: event [guard] / action. All three are optional but the order is fixed.
- Diamond = choose one path (decision/merge). Thick bar = all in parallel (fork/join).
- Swimlane = responsibility. Every action must be in the right lane.
The state machine diagram
Elements
| Element | Notation | Meaning |
|---|---|---|
| State | Rounded rectangle | A condition of the object, in which it stays for some time |
| Initial state | Small filled circle | The starting point |
| Final state | Filled circle inside a ring | The end of the object’s life |
| Transition | Arrow | Moving from one state to another |
| Event | Above the arrow | The occurrence that triggers the transition |
| Guard | [condition] | If true, the transition happens |
| Action | / operation() | Instantaneous work during the transition |
| Activity | do / ... inside the state | Ongoing 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.
| Source | Event [guard] / action | Target |
|---|---|---|
| ● | addToCatalog | Available |
| Available | reserve / startHoldTimer() | On Hold |
| Available | checkOut / setDueDate() | On Loan |
| On Hold | pickUp / setDueDate() | On Loan |
| On Hold | after 48h (holdExpired) | Available |
| On Loan | return | Available |
| On Loan | when today > dueDate | Overdue |
| Overdue | return / chargeFine() | Available |
| Overdue | after 30 days / markLost() | Lost |
| Lost | removeFromCatalog | ◉ |
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
| Element | Notation | Meaning |
|---|---|---|
| Action | Rounded rectangle | A single step (“Place Order”) |
| Activity | Rounded rectangle, with a sub-flow | Work made of several steps |
| Control flow | Solid arrow | Order |
| Object node | Rectangle | A flowing object: Order [paid] |
| Object flow | Arrow (to/from an object) | The flow of data |
| Initial node | Filled circle | Start |
| Activity final | Filled circle inside a ring | Ends the whole flow |
| Flow final | Circle with an X | Ends only that branch |
| Decision | Diamond, [guard] on the outputs | Choose one path |
| Merge | Diamond, several inputs | Join alternative paths |
| Fork | Thick bar, one input many outputs | Start in parallel |
| Join | Thick bar, many inputs one output | Wait for all |
| Swimlane | Strip | The 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?
| Question | Diagram |
|---|---|
| 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 idea | The truth |
|---|---|
| A state machine is for a process | It is for the life cycle of an object |
| Label order action [guard] event | event [guard] / action |
| A state machine for every class | Only 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 = decision | Fork starts in parallel, decision chooses one |
| Merge waits for all branches | Join waits; merge does not wait |
| Showing responsibility without swimlanes | Use swimlanes to show who does it |
| Activity final and flow final are the same | Activity final ends everything, flow final ends a single branch |
Test yourself
Exam-style questions. Solve them on paper first, then reveal the answer.
On a state machine transition labeled returnBook [daysLate > 0] / chargeFine(), identify the event, guard and action.
Show answer
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.
Which kind of class deserves a state machine diagram?
- Every class
- A class whose objects go through clearly different states with different behavior
- Only abstract classes
- Only controller classes
Show answer
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.
In the Copy state machine on this page, how many states (excluding initial and final pseudo-states) are there?
Show answer
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.
In the same Copy state machine, which event moves a copy from On Hold back to Available without a loan?
Show answer
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.
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
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.
In an activity diagram, what is the difference between a decision node and a fork node?
Show answer
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.
Which node waits until ALL incoming parallel flows have finished?
- Merge
- Join
- Decision
- Final
Show answer
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.
What do swimlanes show in an activity diagram?
Show answer
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.
In the food-delivery activity diagram on this page, how many swimlanes and how many fork bars are there?
Show answer
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'.
Write the transition for: 'When a membership expires, if the member has auto-renew on, charge the card.' (from Active)
Show answer
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.
What is the difference between an action and an activity in a state machine?
Show answer
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.