UML Diagrams
Sequence Diagram
Model dynamic behavior, chronological interactions, and message exchanges between objects
A UML Sequence Diagram is an interaction diagram that details how operations are carried out over time. It captures the chronological flow of messages exchanged between objects during a specific scenario. In Low-Level Design, sequence diagrams serve as the dynamic behavioral blueprint, showing exactly how classes coordinate to satisfy functional use cases.
1. Learning Objectives
- Identify sequence diagram components: lifelines, activation bars, and message lines.
- Decode message arrow types: Synchronous, Asynchronous, Return, and Self-Call.
- Employ interaction fragments (
alt,opt,loop, andpar) to represent control flow. - Translate sequence diagrams directly into call stacks and executing methods.
- Construct and trace order checkout workflows in Java, Python, and C++.
2. Problem Statement
Class diagrams show the static connections between components, but they fail to capture the execution sequence. Developing complex transactional logic—like processing credit card checkouts—without modeling dynamic execution leads to:
- Race Conditions & Deadlocks: Objects calling each other in circular loops without a clear sequence, locking up system threads.
- API Interface Gaps: Discovering during coding that a class lacks a public method needed by a caller because the message flow was never traced.
- Cohesion Breakdown: Controllers performing heavy database queries directly instead of delegating to domain services, violating clean architecture.
3. Real-world Analogy
Think of a Theatrical Play Script:
- The Analogy: A theatre script lists the actors across the top or margin. Time runs downward page-by-page. When one actor speaks to another, they send a message. When that actor replies, it is a return message. If an actor speaks a soliloquy to themselves, it is a self-call.
- The Mapping: In software, classes are the actors, lifelines are their presence during execution, and methods are the lines of dialogue they exchange. The script details the exact sequence of events needed to perform a scene.
4. Theory (Diagram Components & Symbols)
A Sequence Diagram represents interaction along two axes: the horizontal axis shows the participating objects, and the vertical axis represents time flowing downwards.
Diagram Components
- Lifelines: Represent participating object instances. Depicted as a box containing the object name (e.g.
orderService: OrderService) with a vertical dashed line extending downwards. - Activation Bars: Thin rectangular boxes drawn over the lifelines. They indicate when an object is actively executing an operation.
- Messages: Horizontal arrows linking lifelines, representing method calls and responses.
Message Symbols
| Message Type | Arrow Notation | Execution Behavior |
|---|---|---|
| Synchronous Call | Solid line with filled arrow (──❯) |
Caller pauses and waits for the method execution to return. |
| Return Message | Dashed line with open arrow (- - ❯) |
Returns control and data back to the caller object. |
| Asynchronous Call | Solid line with open arrow (──❯) |
Caller triggers the action and continues executing without waiting. |
| Self-Call | Looping arrow back to same lifeline | Object invokes its own internal private method. |
Interaction Frames (Control Fragments)
- alt: Alternative block representing conditional logic (
if-else). The block is split by a dashed horizontal line. - opt: Optional block representing conditional execution (
ifwithout else). - loop: Loop block representing iteration (
for,while). - par: Parallel block representing concurrent execution of threads.
5. Visual Diagrams (E-Commerce Checkout Flow)
Below is a Sequence Diagram detailing a successful checkout flow. It uses a loop to check item inventory and an alternative block to process payment results:
6. Syntax Explanation
Sequence diagrams translate directly to code structures:
- Solid Arrow (Method Call): Translated to standard method calls:
controller.processCheckout(cartId). - Dashed Arrow (Return Value): Translated to method return assignments:
boolean isAvailable = invSvc.checkStock(itemId, qty). - Loop Fragment: Translated to loop statements:
for (CartItem item : cart.getItems()). - Alt Fragment: Translated to conditional branches:
if (stockAvailable) { ... } else { ... }.
7. Step-by-Step Creation
- Select Scenario: Do not try to fit every possible system execution path into one diagram. Select a single, focused use case scenario (e.g. Checkout Cart - Success Path).
- Order Lifelines: Place participating objects horizontally across the top. Arrange them logically from left to right based on invocation order (e.g. User -> Controller -> Service -> DB).
- Trace chronological flow: Draw arrows from left to right representing calls, starting from the top. Add return arrows pointing back to the caller.
- Add Activation Bars: Draw rectangular boxes along the dashed vertical lines to show when each object is actively executing code.
- Annotate with Fragments: Draw bounding boxes labeled with fragment types (
alt,loop) around conditional and looping method calls.
8. Complete Code (Mini Project)
9. Code Walkthrough
Let's trace how the sequence diagram's activations map to concrete method execution:
- In
CheckoutController.checkout(), the execution starts. It acts as the controller boundary, instantiating mock cart lists. - The controller invokes
orderService.processCheckout(). This corresponds to message arrow #2. While this execution runs, the activation bar onOrderServiceremains active, and the controller waits synchronously. - Inside the service loop, it calls
inventoryService.checkStock()for each cart item. This pushes a stack frame forcheckStock()(activation bar onInventoryService) and returns a boolean value (message arrow #4). - If the loop completes successfully, the service calls
paymentGateway.charge()(message arrow #5), activating the payment gateway. It returns the charging confirmation (message arrow #6). - Finally, the service returns the generated order ID back to the controller, and the controller displays the checkout confirmation.
10. Execution Flow
- Initial Trigger: External client triggers
controller.checkout("CART_1234"). - Inventory Validation Loop: Service iterates over items. Each call to
checkStock()executes sequentially, pausing the service thread execution until it returns. - Conditional Charge (Alt): If stock checks succeed, the system executes
charge(). If checks fail, the system throws a runtime exception, bypassing the charge step. - Completion: Control returns to the controller. The activation frame ends, and resources are cleared.
11. Internal Working (The Call Stack Mapping)
There is a direct correlation between the vertical structure of a sequence diagram and the JVM/CPU call stack:
- Stack Frame Allocation: When a method is called (e.g.
processCheckout()), a stack frame containing local variables and return addresses is pushed onto the thread's call stack. This allocation event corresponds to the start of the activation bar on the sequence diagram. - Stack Depth: As one class calls another, the stack depth increases. When
processCheckout()callscheckStock(), a new frame is pushed on top of the stack. This nesting corresponds to horizontal arrow progression. - Frame Popping: When a method returns, its stack frame is popped, freeing thread stack space. This matches the end of the activation bar and the return dashed arrow.
12. Complexity Analysis
- Time Complexity: $O(U)$ where $U$ is the number of sequential message paths. Tracing sequence paths helps developers identify unnecessary nested loop queries.
- Space Complexity: $O(D)$ where $D$ is the maximum call stack depth. A deep call hierarchy consumes more stack frame memory.
13. Best Practices
- Focus on a single scenario: Avoid drawing a massive diagram that attempts to show every possible error and success path. Use different diagrams for different paths.
- Order lifelines chronologically: Arrange objects horizontally based on their activation sequence to minimize crossing lines.
- Keep messages abstract: Label arrows with actual method signatures from your class designs to maintain consistency.
- Use activation bars correctly: Ensure activation bars accurately represent the lifespan of the method on the execution stack.
14. Common Mistakes
- Modeling static structures instead of dynamic interactions: Drawing permanent associations instead of time-ordered method calls.
- Flowcharting details: Trying to represent low-level arithmetic operations or variable assignments (e.g.
x = x + 1) as message arrows. - Incorrect fragment boxes: Using an
optbox for anif-elsechoice instead of analtbox.
15. Interview Questions
Answer: Both show object interactions. However, Sequence Diagrams emphasize time order, showing chronological flow down the vertical axis. Communication Diagrams focus on static structural linkages, using numbered arrows to show interaction paths.
Answer: By using a solid line with an open arrow head (
──❯). This indicates that the sender continues executing immediately without pausing for a response.
Answer: The activation bar represents the period during which an object is executing an operation. It corresponds directly to the active method frame on the thread's call stack.
16. Practice Exercises
- Easy: Draw a Sequence Diagram showing a User borrowing a Book from a Library system. Include checking availability and marking the book as borrowed.
- Medium: Draw a Sequence Diagram representing a customer withdrawing cash from an ATM. Model the PIN validation check (include) and optional receipt printing (extend).
- Hard: Design a Sequence Diagram for an Uber-style ride matching flow. Show interactions between Passenger, RideController, Driver, and LocationService. Model location polling loops and payment validation.
17. Challenge Problem
Design a Sequence Diagram for a Distributed Movie Ticket Booking System (like Ticketmaster). The scenario involves a customer selecting and reserving a seat. The reservation triggers a 10-minute lock timer. If the customer pays within 10 minutes, the booking is confirmed and ticket PDFs are generated. If the timer expires before payment, the seat lock is released. Represent this flow including the asynchronous timer callback and the alternative payment branches. Write the corresponding class flow in Java, Python, or C++.
18. Summary
- Sequence Diagrams show the chronological order of method interactions between objects.
- The horizontal axis represents objects/lifelines; the vertical axis represents time flowing downwards.
- Synchronous calls block execution, while Asynchronous calls trigger actions and return immediately.
- Interaction fragments (
alt,opt,loop) represent standard control flow structures in diagrams.
19. Cheat Sheet
| Element | Visual Symbol | Execution Equivalent | Stack Action |
|---|---|---|---|
| Synchronous Message | Solid line, filled arrow (──❯) |
Standard blocking method call | Pushes a new frame onto the stack |
| Return Message | Dashed line, open arrow (- - ❯) |
Method return value | Pops the top frame off the stack |
| Asynchronous Message | Solid line, open arrow (──❯) |
Trigger background thread/event | Spawns a new stack trace on another thread |
| alt Fragment | Labeled bounding box with partitions | if-else conditional statement |
Conditional branching execution path |
20. Quiz
1. Which axis of the UML Sequence Diagram represents time?
A) The horizontal axis
B) The vertical axis (Correct)
C) The diagonal axis
2. What does a vertical dashed line extending below an object box represent?
A) An inheritance connection
B) An activation state
C) A lifeline (Correct)
3. How is a standard synchronous method call represented visually?
A) Dashed line with open arrow
B) Solid line with filled arrow (Correct)
C) Solid line with open arrow
4. How is a method return message represented?
A) Solid line with open arrow
B) Dashed line with open arrow (Correct)
C) Dashed line with filled arrow
5. Which fragment box is appropriate for modeling an if-else condition?
A) opt
B) par
C) alt (Correct)
6. What does the height of an activation bar correspond to in terms of runtime execution?
A) The memory allocated on the heap
B) The lifespan of the method frame on the thread's call stack (Correct)
C) The speed of the JIT compilation
7. What notation is used to represent an asynchronous message call?
A) Solid line with an open arrow (Correct)
B) Dashed line with an open arrow
C) Solid line with a filled arrow
8. Which fragment box represents parallel/concurrent execution?
A) loop
B) alt
C) par (Correct)
9. What is a common mistake when drawing sequence diagrams?
A) Showing return arrows
B) Representing static class references instead of dynamic method calls (Correct)
C) Using activation bars
10. What fragment is used to represent optional execution without an else branch?
A) alt
B) opt (Correct)
C) loop
21. Next Lesson Preview
In the next lesson, we will cover the Activity Diagram. We will explore how to model workflows and operational logic using decisions, merges, forks, and joins!