UML: Sequence, Activity & State Diagrams

Fragments: alt, opt & loop

18 min Lesson 4 of 10

Fragments: alt, opt & loop

A basic sequence diagram captures the happy path — the straight-line exchange of messages when everything works perfectly. Real systems are rarely that simple. A patient may or may not be a registered member. A payment can succeed or fail. A retry must repeat until the server responds. Combined fragments are the UML mechanism that lets you model all of these branching and repeating behaviors inside a single sequence diagram without drawing multiple diagrams for every scenario.

What Is a Combined Fragment?

A combined fragment is a rectangular frame drawn directly on the sequence diagram canvas, surrounding a group of messages. The frame has a small pentagon label in its top-left corner called the interaction operator — this tells you whether the frame represents a conditional, an optional block, a loop, or one of several other behaviors. The three operators you will use most often are alt, opt, and loop.

Inside the frame you can divide the space into operands using a dashed horizontal line. Each operand may carry a guard condition written in square brackets, such as [payment successful] or [member discount > 0]. Guards are Boolean expressions evaluated at runtime to decide which operand executes.

The alt Fragment — Conditional Branches

The alt operator (short for alternatives) models an if / else if / else structure. Exactly one of the operands executes at runtime, determined by which guard is true. This maps directly onto the decision points that analysts discover when eliciting requirements: "If the user is logged in, skip registration; otherwise, show the sign-up form."

Key rule: In an alt fragment, exactly one operand fires. If you have an unconditional fallback, write the last guard as [else], mirroring the else clause in code.

The diagram below models a clinic booking system. When a patient requests an appointment, the system checks availability. Two branches exist: if a slot is free the booking is confirmed; if no slot is free a waitlist offer is returned.

alt fragment — clinic appointment booking Patient BookingSystem Database requestAppointment(date, time) checkSlot(date, time) slotAvailable alt [slot is available] confirmBooking(bookingId) sendConfirmationEmail() [else — no slot available] offerWaitlist(date) addToWaitlist(patientId) waitlistConfirmation()
Figure 1 — alt fragment: the clinic system confirms a booking or offers a waitlist depending on slot availability.

The opt Fragment — Optional Behavior

The opt operator (short for optional) models a block of messages that executes only if the guard is true. If the guard is false the entire block is skipped. Think of it as an if with no else.

opt is syntactic sugar — a single-operand alt — but using it signals to the reader that skipping the block is a perfectly normal outcome, not an error path. A classic use: "Apply a loyalty discount only if the customer has enough points."

When to use opt vs alt: Use opt when there is only one meaningful branch and doing nothing is the natural alternative. Use alt when two or more specific behaviors compete.

The loop Fragment — Repetition

The loop operator surrounds a block that repeats. You specify bounds in parentheses after the keyword: loop(min, max). You can also add a guard condition that is re-evaluated before each iteration — the loop exits when the guard becomes false or the maximum count is reached. The minimum bound (often 0 or 1) states the guaranteed number of executions before the guard is checked.

Common notations you will encounter:

  • loop(1, *) — repeat at least once, indefinitely while the guard holds.
  • loop(0, 3) — repeat zero to three times.
  • loop(1, 1) — execute exactly once (rarely written explicitly, but valid).

The diagram below shows an online store order-processing flow, combining a loop for retrying a payment gateway and an opt for an optional gift-wrapping step.

loop and opt fragments — online store order processing Customer OrderService PaymentGateway placeOrder(cartId, giftWrap) loop (1, 3) [payment not confirmed] chargeCard(amount) paymentResult(status) logAttempt(status) retryAck() opt [giftWrap == true] notifyGiftWrap(message) scheduleGiftWrap(orderId) orderConfirmed(orderId)
Figure 2 — loop and opt fragments: payment is retried up to three times; gift-wrapping is applied only when the customer requested it.

Nesting Fragments

Fragments can be nested inside each other. A loop may contain an alt, and an alt operand may itself contain an opt. When nesting, keep the outer frame visually distinct (a slightly thicker border or a different stroke color in your drawing tool). The rule is simple: the innermost frame takes precedence for the messages it contains, just as inner conditional blocks do in code.

Avoid deep nesting in diagrams you share with stakeholders. A diagram with three levels of nested fragments is technically correct but practically unreadable. If nesting goes beyond two levels, consider splitting the interaction into a separate referenced sequence diagram using a ref fragment — another interaction operator that delegates to a named diagram.

How Analysts Use Fragments in Practice

When you are modeling a use-case scenario, walk through each step and ask three questions:

  1. Is there a decision here? If yes and there are two or more specific outcomes, use alt. If yes and the only alternative is "do nothing", use opt.
  2. Does a set of messages repeat? If yes, use loop and write the termination condition as the guard.
  3. Are two things happening in parallel? Use a par fragment (parallel — covered in the Activity Diagrams lesson).

For the library system, imagine the workflow of checking out a book: the system must verify membership validity (opt: apply a late-fee waiver for premium members), attempt an RFID scan with retries (loop: up to 3 scans), and route to either a success or an overdue-check path (alt). Modeling this with fragments on one diagram gives a stakeholder a richer, more honest view of the process than a simple linear diagram ever could.

Analyst habit: Write guard conditions in plain business language first — [customer is premium member], not [memberType == 2]. Guards should communicate intent to stakeholders, not implementation details to developers.

Summary

  • A combined fragment is a labeled rectangular frame that adds conditional or repetitive logic to a sequence diagram.
  • alt — mutually exclusive branches separated by a dashed dividing line; guards determine which fires; use [else] as the unconditional fallback.
  • opt — a single optional block that executes only when its guard is true; equivalent to an if with no else.
  • loop(min, max) [guard] — repeats the enclosed messages; exits when the guard is false or the maximum count is reached.
  • Fragments can nest; keep nesting shallow and write guards in business language for stakeholder readability.