Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 39 ยท Sequence and Communication Diagrams

Alternatives, Loops and Combined Fragments

Add logic to sequence diagrams with combined fragments: alt, opt, loop, par, break, critical and ref, with guards, examples, and advice on when to split a diagram instead.

A basic sequence diagram shows one straight path. Real scenarios branch, repeat and overlap. UML handles this with combined fragments: labelled boxes drawn over part of the diagram. The label in the top-left corner, called the operator, says what kind of logic the box contains, and guards in square brackets state the conditions.

alt: if / else

alt (alternatives) has two or more operands separated by dashed lines. Exactly one operand runs, chosen by its guard.

sequenceDiagram
    actor U as Customer
    participant S as OrderService
    participant P as PaymentGateway
    U->>S: pay(order)
    S->>P: charge(card, total)
    alt payment accepted
        P-->>S: approved
        S-->>U: receipt
    else card declined
        P-->>S: declined
        S-->>U: show error
    end

Either branch is shown in the same diagram, so the two outcomes of charge are visible at once.

An [else] operand catches everything not covered by the other guards. Keep guards mutually exclusive.

opt: an optional part

opt is an alt with only one operand: the content runs if the guard is true, otherwise it is skipped.

sequenceDiagram
    participant S as OrderService
    participant C as CouponService
    participant B as BillingService
    S->>B: createInvoice(order)
    opt customer entered a coupon
        S->>C: redeem(code)
        C-->>S: discount
        S->>B: applyDiscount(discount)
    end
    S->>B: finalize()

The coupon steps run only when a code was entered.

loop: repetition

loop repeats its content. The guard can be a condition (while items remain), a count (3 times) or a range loop(1,5) (at least 1, at most 5 repetitions).

sequenceDiagram
    participant S as OrderService
    participant I as Inventory
    loop for each line item
        S->>I: reserve(sku, qty)
        I-->>S: reserved
    end
    S->>S: markOrderConfirmed()

One reserve call per order line.

par: parallel messages

par runs its operands concurrently; the order between operands is unspecified.

sequenceDiagram
    participant S as OrderService
    participant M as MailService
    participant W as Warehouse
    participant A as Analytics
    S->>S: finishOrder()
    par send mail
        S->>M: sendReceipt()
    and prepare shipment
        S->>W: createPickList()
    and track event
        S->>A: record(orderPlaced)
    end

Three independent things happen at once. This is the sequence-diagram equivalent of fork and join.

Other operators

Operator Meaning Typical use
alt choose one of several operands success versus failure
opt run if the guard holds optional step
loop repeat iterate over items
par run operands in parallel independent notifications
break leave the enclosing fragment if guard holds stop on error
critical no interleaving with other traces exclusive access
neg traces that must not occur forbidden behavior
ref refers to another interaction reuse a sub-scenario
seq, strict weak or strict ordering rare
ignore, consider, assert which messages matter, or must hold formal use

Mermaid supports alt, opt, loop, par, critical and break directly. For ref, you write a note or a rectangle over the participants.

sequenceDiagram
    participant U as User
    participant A as AuthService
    participant S as Shop
    rect rgb(235, 240, 250)
        Note over U,A: ref Authenticate
    end
    U->>S: checkout()
    break session expired
        S-->>U: redirect to login
    end
    S-->>U: confirmation

A grey box labelled ref Authenticate points to another sequence diagram. The break fragment ends the scenario early.

Nesting fragments

Fragments nest. A loop can contain an alt. Keep nesting to two levels; deeper nesting means the diagram is doing too much.

sequenceDiagram
    participant S as OrderService
    participant I as Inventory
    participant N as Notifier
    loop for each line item
        S->>I: reserve(sku, qty)
        alt out of stock
            I-->>S: unavailable
            S->>N: notifyBackorder(sku)
        else in stock
            I-->>S: reserved
        end
    end

When to split into several diagrams

A diagram full of fragments stops being a readable script. Prefer separate diagrams when:

  • The main scenario and its error scenarios differ a lot. Draw the happy path, then one diagram per important failure.
  • You need more than two nested fragments.
  • The fragment contains a reusable sub-scenario (use ref and give it its own diagram).
  • Different audiences need different detail.

Fragment operators

alt One of several branches.
opt Maybe, if guard holds.
loop Repeat.
par At the same time.

Guards go in [square brackets].

1 / 2

From fragments to code

The fragments map directly to control structures, which makes sequence diagrams a good starting point for implementation.

Python alt, opt and loop as plain code

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python par as concurrent tasks, and why order is unspecified

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python Check a trace against an alt guard

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Common mistakes

  • Missing guards. An alt with unlabeled operands is ambiguous.
  • Overlapping guards. More than one operand could be true.
  • Using par for things that depend on each other.
  • Deep nesting. More than two levels is a signal to split.
  • Putting every error in one diagram. The result hides the main flow.

Write the guard as a short condition in plain words ("card declined"), not as code. The diagram is for people first.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which fragment models if/else?

    alt has several operands with guards; exactly one runs. opt has only one.
  2. 2. What does opt mean?

    opt is an optional section controlled by a guard.
  3. 3. Where are guards written?

    Guards are conditions in square brackets: [card declined].
  4. 4. When is it best to split a sequence diagram instead of adding fragments?

    Readable diagrams show one clear scenario; split large variations into their own diagrams.

Summary

  • Combined fragments add branches, loops and concurrency to sequence diagrams.
  • alt for if/else, opt for optional, loop for repetition, par for parallel, break to exit, ref to reuse another interaction.
  • Guards in square brackets state the conditions; keep them exclusive.
  • Fragments map almost directly to code control structures.
  • Limit nesting; split into several diagrams when a fragment-rich diagram gets hard to read.

Next: Lifelines, Gates and Interaction Use