SEN2022 · Week 10 · Behavioral Modeling

Behavioral modeling 1: sequence and communication diagrams

Objects exchanging messages in time order to realize a use case: lifelines, activations, message types, alt/opt/loop fragments, and the same information as a communication diagram. On the exam you are asked to draw a sequence diagram for a scenario.

behavioral modelinteraction diagramsequence diagramlifelineactivation (execution occurrence)synchronous messageasynchronous messagereturn messagecreate messagedestroycombined fragmentaltoptloopguard conditioncommunication diagramlinksequence numberCRUDE matrix

The functional model (use case) said what the system does, and the structural model (class diagram) said with which objects it does it. The behavioral model shows how these objects work together over time. There are three kinds of diagrams: interaction diagrams (sequence and communication), behavioral state machines (state machine), and the activity diagram that often accompanies them. This page covers the interaction diagrams; the second page covers the state machine and activity diagram.

The exam question is mostly: “Draw a sequence diagram for the normal flow of use case X.” You read the use case description step by step and turn each step into one or more messages.

Golden rules:

  1. One diagram = one scenario of one use case.
  2. Lifelines come from the classes in the class diagram. If you invented a new class, add it to the class diagram too.
  3. A message is an operation of the receiver. The class that receives the checkEligibility() message must have this operation.
  4. Watch the arrowheads: filled = synchronous, open = asynchronous, dashed = return.

Elements of the sequence diagram

ElementNotationMeaning
ActorStick figure, with a lifeline under itThe role that starts the interaction
Object / lifelineAn anOrder : Order box + dashed vertical lineAn object taking part in the interaction
ActivationNarrow rectangle on the lifelineThe period when the object is active
Synchronous messageSolid line, filled arrowA call, a reply is expected
Asynchronous messageSolid line, open arrowSend and continue
Return messageDashed line, open arrowReturn value
Create message<<create>> or create(), the target box is at that levelA new object is created
DestroyX at the end of the lifelineThe object is destroyed
Guard[condition]The message is sent only if the condition is true
Combined fragmentFrame, with alt, opt, loop at the top leftControl structure

Writing the object name: aStudent : Student (a specific object), : Copy (an anonymous object of that class). In analysis, anonymous objects are usually used.

Combined fragments

FragmentCode equivalentExample guard
altif / else[copy exists] / [else]
optif (no else)[total > 300]
loopfor / while[for each cart item]
parparalleltwo compartments at the same time

How to draw a sequence diagram

  1. Choose the use case and the scenario (usually the normal flow).
  2. Identify the participating actor and objects; arrange them from left to right, with the first one to speak on the left.
  3. Draw the lifelines. Put objects created later at the level where they are created.
  4. Turn every step of the description into a message, in order from top to bottom.
  5. Add the activation boxes.
  6. Show conditions and repetitions with fragments.
  7. Check: does the receiver of each message have that operation? Is it consistent with the class diagram?

Worked example: Reserve Book

The normal flow of the fully dressed description in week 7. In analysis, putting a control object (ReservationController) in between organizes the flow: the actor talks to this object, and it manages the other objects.

S = aStudent   C = :ReservationController
B = :Book      K = :Copy
R = :Reservation (born with message 4)

 S        C        B        K
 |        |        |        |
 |--1---->|        |        |
 |        |--2---->|        |
 |        |<- 2r- -|        |
 |        |--3--+  |        |
 |        |<----+  |        |
 |        |--4 create------------>[ R ]
 |        |--5------------->|       |
 |        |--6 (async)------------->|
 |<--7----|        |        |       |
 |        |        |        |       |

The numbers are the messages in the table below; 2r is the return of message 2 (the copy list). Message 3 is a message C sends to itself (self-call). The R box does not start at the top but at the level of message 4. On the exam this table and the drawing complement each other.

NoSenderReceiverMessageType
1aStudent:ReservationControllersearchBook(query)Synchronous
2:ReservationController:BookgetAvailableCopies()Synchronous, return: copy list
3:ReservationController:ReservationControllercheckEligibility(student)Message to itself (self-call)
4:ReservationController:Reservationcreate(student, copy)Create, Reservation is born here
5:ReservationController:CopysetStatus(“On Hold”)Synchronous
6:ReservationController:ReservationsendConfirmation()Asynchronous (the e-mail is not waited for)
7:ReservationControlleraStudentshowConfirmation(code)Synchronous, displaying the reply

Count: 5 lifelines (aStudent, :ReservationController, :Book, :Copy, :Reservation), 7 messages (excluding returns).

Adding an alternate flow: the alt fragment

If 3a (“no available copy”) is added, an alt frame comes after message 2:

+-alt-----------------------------------+
| [copy list not empty]                 |
|   3 checkEligibility ... 7 showConf.  |
|- - - - - - - - - - - - - - - - - - - -|
| [else]                                |
|   3' offerWaitingList()               |
+---------------------------------------+

PITFALL · forcing a return onto every message. A return message is drawn only when a meaningful value is returned (the copy list, the reservation code). Putting a dashed arrow on every synchronous call clutters the diagram but is not wrong; the real mistake is mixing up synchronous and asynchronous.

Communication diagram

The same interaction, shown on the links between objects. There is no time axis; the order is read from the numbers. It shows at a glance who talks to whom (the structure).

               :Book
                 |  2: getAvailableCopies()
                 |
 aStudent ------ C ------ :Copy
 1: searchBook(q)|  5: setStatus("On Hold")
 7: showConf()   |
                 |  4: create()
                 |  6: sendConfirmation()
            :Reservation

 C = :ReservationController
 A link from C to itself: 3: checkEligibility()

Numbering rules:

NumberMeaning
1, 2, 3Top-level messages sent in order
2.1, 2.2Sent while handling message 2 (nested)
2.1.1Sent inside 2.1
*[i=1..n]Repetition (iteration)
[condition]Guard

Example: if :Book asked each copy for its status while handling getAvailableCopies(), these messages would be written as 2.1 *[each copy]: getStatus().

Sequence or communication?

CriterionSequenceCommunication
EmphasisTime orderObject connections
ReadingTop to bottomFrom the numbers
Fragments (alt/opt/loop)YesLimited (with guard and *)
Interaction with many objectsWidens, overflows horizontallyMore compact

The two diagrams carry the same information; some tools generate one from the other automatically.

The CRUDE matrix

After the sequence diagrams, a table can be built that summarizes how the classes interact with each other.

StudentBookCopyReservation
ReservationControllerRRRUCE
ReservationRR

Reading a cell: ReservationController Creates the Reservation object and Executes one of its operations (sendConfirmation). It reads and updates Copy (R, U). If a class never sends a message to another but there is a relationship between them in the class diagram, question whether the relationship is needed (week 11).

Common mistakes

Wrong ideaThe truth
Putting the whole system in one sequence diagramOne use case, one scenario
Putting a class that is not in the class diagram on a lifeline and leaving itAdd the new class to the class diagram too
Synchronous and asynchronous arrows are the sameFilled arrow synchronous, open arrow asynchronous
A return is a solid lineA return is a dashed line
opt for if/elsealt for if/else; opt is a single condition, no else
A communication diagram has no orderThe order is shown by the numbers
2.1 comes after 32.1 is inside 2; it ends before 3
Drawing the created object at the topIt starts at the level of the create message

Test yourself

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

Question 1easy

What does a sequence diagram emphasize compared to a communication diagram?

  1. The time order of messages
  2. The structure of links between objects
  3. The states of one object
  4. The attributes of classes
Show answer
A) The time order of messages

A sequence diagram shows time on the vertical axis: the order of messages from top to bottom. A communication diagram shows the same messages with numbers on the links between objects; it emphasizes the structure, and the order is read from the numbers.

Question 2easy

In a sequence diagram, what is the thin rectangle drawn on a lifeline?

Show answer
An activation (execution occurrence): the period when the object is performing an operation.

A lifeline is the dashed vertical line showing the existence of the object. The narrow rectangle on it is the activation: during that time the object is doing some work or waiting for the call it made to return.

Question 3medium

Which arrow represents a synchronous message?

  1. Solid line with a filled arrowhead
  2. Solid line with an open arrowhead
  3. Dashed line with an open arrowhead
  4. Line with a hollow triangle
Show answer
A) Solid line with a filled arrowhead

Synchronous message: solid line, filled arrowhead; the sender waits for the reply. Asynchronous: solid line, open (line) arrowhead; the sender does not wait. Return: dashed line, open arrowhead. The hollow triangle is generalization and is not used in a sequence diagram.

Question 4easy

Which combined fragment shows that a group of messages happens only if a condition is true, with no else branch?

  1. alt
  2. opt
  3. loop
  4. par
Show answer
B) opt

opt: a single compartment, runs if the condition is true. alt: if/else, several compartments each with its guard. loop: repetition. par: parallel compartments.

Question 5medium

How many messages (excluding return messages) are in the Reserve Book sequence diagram on this page?

Show answer
7

1 searchBook, 2 getAvailableCopies, 3 checkEligibility, 4 create (Reservation), 5 setStatus, 6 sendConfirmation, 7 showConfirmation. The returns (dashed arrows) were not counted separately. Total 7 messages.

Question 6easy

How many lifelines are in the same diagram?

Show answer
5

aStudent (the actor), :ReservationController, :Book, :Copy, :Reservation. Because Reservation is created in the middle of the diagram by a create message, its box starts lower down, but it is still a lifeline.

Question 7medium

In a communication diagram, a message is numbered 2.1. What does that mean?

Show answer
It is the first message sent while handling message 2 (nested inside message 2).

Nested numbering shows the call structure: the object that receives message 2 sends 2.1 and 2.2 while doing its work. 3 comes after 2 has completely finished.

Question 8hard

Food-delivery: 'The customer submits an order. The OrderController creates an Order. For each item in the cart, the Order creates an OrderLine. If the total is over 300 TL, a free-delivery flag is set.' Which fragments do you need?

Show answer
loop (for each item) around OrderLine creation, and opt [total > 300] around setting the free-delivery flag.

A repeated message goes into a loop frame (guard: [for each item]). A conditional message with no else goes into an opt frame (guard: [total > 300]). If there were an else, alt would be used.

Question 9easy

What does an X at the bottom of a lifeline mean?

Show answer
The object is destroyed at that point.

The large X at the end of a lifeline shows that the object is destroyed. Example: a temporary Reservation object whose time has expired.

Question 10medium

In the CRUDE matrix, what does each letter stand for?

Show answer
Create, Read, Update, Delete, Execute

The CRUDE matrix is a table with the classes in the rows and the columns. A cell shows how the class in the row interacts with the class in the column: Create, Read, Update, Delete, Execute. It is filled in from the messages in the sequence diagrams and is used to verify relationships between classes.

Question 11easy

A sequence diagram is usually drawn for what scope?

  1. The whole system at once
  2. One scenario of one use case
  3. One class only
  4. The physical network
Show answer
B) One scenario of one use case

A sequence diagram is usually drawn for one scenario of a use case (mostly the normal flow). For important alternate flows, a separate diagram or an alt fragment is added. Putting the whole system in one diagram makes it unreadable.

Verification: Conceptual and drawing/counting questions were checked against the UML 2 interaction diagram rules (synchronous message with a filled arrowhead, asynchronous with an open arrowhead, return as a dashed line; alt/opt/loop fragments; nested numbering 1, 1.1, 1.2 in the communication diagram). The numbers of messages and lifelines in the diagrams on the page were counted by hand and compared twice.

Review card

Behavioral model: HOW objects work together over time Sequence: time from top to bottom, emphasis on order Lifeline: object box + dashed vertical line; actor stick figure Activation: narrow box on the lifeline (the object is working) Synchronous: solid line + FILLED arrow; Asynchronous: solid + OPEN arrow Return: DASHED line + open arrow create: the created object's box starts at the message level; X = destroy Fragment: alt (if/else), opt (if), loop (repetition), par (parallel) Guard: [condition] in square brackets Communication: the same information, numbered messages on links Numbering: 1, 1.1, 1.2, 2 → nested call CRUDE matrix: Create Read Update Delete Execute Scope: one use case, one scenario