Software EngineeringUnit 412 min read
UML Modelling: Diagrams, Classes, Use Cases & State Machines
Unit 4 of Software Engineering covers Unified Modeling Language (UML)—its 14 diagrams, class diagrams with associations/aggregations, use case diagrams for workflows, state machines for dynamic behavior, and activity diagrams for processes—with real-world examples from Nepalese apps (eSewa, Daraz) and global systems (G
What is UML?
Unified Modeling Language (UML) is a standardized visual language for designing, visualizing, and documenting software systems. Developed in 1997 by the Object Management Group (OMG), it provides 14 diagram types to model different aspects of a system:
- Structural diagrams (what the system is): class, object, component, deployment, package, profile.
- Behavioral diagrams (what the system does): use case, activity, state machine, sequence, communication, interaction overview, timing.
UML is language-agnostic (works for Java, Python, C++, etc.) and platform-independent, making it essential for software architects, developers, and testers.
Why Use UML?
- Clarity: Replaces ambiguous text descriptions with precise visual models.
- Communication: Bridges gaps between stakeholders, developers, and testers.
- Reusability: Models can be reused in different projects.
- Standardization: Ensures consistency across teams (like a "blueprint" for software).
The 14 UML Diagrams (Focus on 5 Key Ones)
The syllabus emphasizes class, use case, state machine, activity, and sequence diagrams. Below are the most exam-relevant ones with real-world ties.
1. Class Diagram (Structural)
Definition: Shows classes, their attributes, methods, and relationships (association, aggregation, inheritance, composition). Key Elements:
- Class: Rectangle divided into 3 parts:
- Top: Class name (e.g.,
Customer). - Middle: Attributes (
-id: int,+name: String). - Bottom: Methods (
+placeOrder(),-calculateTax()).
- Top: Class name (e.g.,
- Relationships:
- Association (dashed line): General link (e.g.,
Customer↔Order). - Aggregation (hollow diamond): "Has-a" (e.g.,
Department◁—Employee). - Composition (filled diamond): "Owns-a" (e.g.,
Car◆Engine). - Inheritance (solid line with arrow): "Is-a" (e.g.,
Student→Person).
- Association (dashed line): General link (e.g.,
Worked Example: Daraz Order System
classDiagram
class Customer {
-customerID: int
-name: String
+placeOrder()
}
class Order {
-orderID: int
-items: List~Product~
+calculateTotal()
}
class Product {
-productID: int
-price: double
-stock: int
}
Customer "1" --> "*" Order : places
Order "1" --> "*" Product : containsReal-World Tie:
- When you add items to your Daraz cart, the system uses a composition relationship (
OrderownsProductinstances). - If you cancel an order, the
Orderclass’scancel()method triggers updates in theCustomerandProductclasses.
Comparison Table: Relationships
| Relationship | Symbol | Meaning | Example |
|---|---|---|---|
| Association | Dashed line | General link | User ↔ Post (Facebook) |
| Aggregation | Hollow diamond (◁—) | "Has-a" (weak ownership) | University ◁— Department |
| Composition | Filled diamond (◆) | "Owns-a" (strong ownership) | House ◆ Room |
| Inheritance | Solid line (→) | "Is-a" (subclass) | Dog → Animal |
2. Use Case Diagram (Behavioral)
Definition: Models system interactions from the user’s perspective, showing actors (users/roles) and use cases (actions). Key Elements:
- Actor: External entity (e.g.,
Customer,Admin). - Use Case: Oval representing a functionality (e.g.,
Place Order,Cancel Order). - Relationships:
- <<includes>>: Mandatory sub-process (e.g.,
Place Order<<includes>>Payment). - <<extends>>: Optional sub-process (e.g.,
Apply Discount<<extends>>Checkout).
- <<includes>>: Mandatory sub-process (e.g.,
Worked Example: eSewa Payment System
classDiagram
actor User
actor Merchant
User --> (Pay Bill) : triggers
User --> (Transfer Money) : triggers
User --> (Check Balance) : triggers
Merchant --> (Receive Payment) : triggers
(Pay Bill) ..> (Transfer Money) : <<includes>>
(Pay Bill) ..> (Send SMS) : <<extends>>Real-World Tie:
- When you pay a NTC bill via eSewa, the system follows:
UserselectsPay Bill(use case).- The system includes
Transfer Money(deducts from your wallet). - Optionally extends
Send SMS(notifies you of success/failure).
Advantages of Use Case Diagrams
- User-centric: Focuses on what the user does, not how.
- Early requirements capture: Helps identify missing functionalities.
- Stakeholder alignment: Non-technical users (e.g., clients) can visualize workflows.
3. State Machine Diagram (Behavioral)
Definition: Models object behavior over time, showing states, transitions, and events. Key Elements:
- State: Rectangle (e.g.,
Order Placed,Order Shipped). - Transition: Arrow with event [guard condition]/action (e.g.,
on Payment Success → Shipped). - Initial State: Black circle.
- Final State: Circle with a cross.
Worked Example: Pathao Ride Status
stateDiagram-v2
[*] --> Waiting: Rider requests ride
Waiting --> RideAssigned: Driver accepts
RideAssigned --> RideInProgress: Driver starts trip
RideInProgress --> RideEnded: Passenger arrives
RideEnded --> [*]: Trip completed
RideAssigned --> Waiting: Driver rejectsReal-World Tie:
- When you book a Pathao ride, your order goes through these states:
Waiting→RideAssigned(driver picks up).- If the driver rejects, it loops back to
Waiting. - On arrival, it transitions to
RideEnded.
When to Use State Machines
- Systems with clear lifecycle stages (e.g., order processing, traffic light control).
- Event-driven systems (e.g., WhatsApp message status:
Sent→Delivered→Read).
4. Activity Diagram (Behavioral)
Definition: Models workflows/processes as flowcharts, showing actions, decisions, and parallel paths. Key Elements:
- Action: Rounded rectangle (e.g.,
Check Stock). - Decision: Diamond (e.g.,
Is Stock Available?). - Merge: Inverted diamond (combines paths).
- Fork/Join: Parallel bars (for concurrency).
Worked Example: Khalti Payment Flow
flowchart TD
A["Start"] --> B["User Selects Pay"]
B --> C{"Is Wallet Balanced?"}
C -->|"Yes"| D["Deduct Amount"]
C -->|"No"| E["Redirect to Bank"]
D --> F["Send Confirmation SMS"]
E --> F
F --> G["End"]Real-World Tie:
- When you pay via Khalti:
- The system checks
Is Wallet Balanced?. - If No, it forks to bank payment (parallel to SMS confirmation).
- Both paths merge at
Send Confirmation SMS.
- The system checks
Activity vs. State Machine
| Feature | Activity Diagram | State Machine Diagram |
|---|---|---|
| Focus | Workflow/process steps | Object lifecycle |
| Use Case | Business processes (e.g., loan approval) | Object behavior (e.g., traffic light) |
| Concurrency | Supports fork/join | Limited to state transitions |
| Example | Online shopping cart | ATM transaction states |
5. Sequence Diagram (Behavioral)
Definition: Shows object interactions in time order, highlighting messages passed between actors/objects. Key Elements:
- Lifeline: Vertical dashed line (represents an object).
- Message: Arrow with label (e.g.,
placeOrder()). - Activation Bar: Thin rectangle (shows when an object is active).
- Return Message: Dotted arrow.
Worked Example: Nepse Stock Trade
sequenceDiagram
participant User
participant BrokerApp
participant NepseServer
User->>BrokerApp: placeOrder(BUY, 100 shares)
BrokerApp->>NepseServer: validateOrder()
NepseServer-->>BrokerApp: OrderValid
BrokerApp->>NepseServer: executeTrade()
NepseServer-->>BrokerApp: TradeConfirmed
BrokerApp->>User: showConfirmation()Real-World Tie:
- When you buy shares on NEPSE via a broker app:
- Your
BrokerAppsendsplaceOrder()toNepseServer. NepseServervalidates and executes the trade.- The app shows
TradeConfirmedto you.
- Your
Key Patterns in Sequence Diagrams
- Synchronous Call: Solid arrow (waits for response).
- Asynchronous Call: Sticky arrow (no wait).
- Loop:
loopkeyword (e.g.,loop until stock available). - Alternative:
alt/else(e.g.,alt success else failure).
In the Real World
eSewa (Nepal)
- Use Case Diagram: Models
Pay Bill,Transfer Money, andCheck Balancefor users. - State Machine: Tracks
Payment Initiated→Processing→Completed/Failed.
- Use Case Diagram: Models
Daraz (Nepal)
- Class Diagram:
Customer(placesOrder),Order(containsProduct),Cart(aggregatesProduct). - Activity Diagram: Shows
Add to Cart→Checkout→Payment→Ship Orderworkflow.
- Class Diagram:
Google Maps (Global)
- Sequence Diagram:
User→Google Maps→GPS Server→Route Calculation→Display Route. - State Machine:
Navigationstates:Route Planned→In Progress→Arrived.
- Sequence Diagram:
Ncell Recharge
- Use Case:
Customer→Recharge<<includes>>Payment<<extends>>Send Receipt.
- Use Case:
Bank Loan Processing (Global)
- Activity Diagram:
Apply Loan→Check Credit Score(decision) →Approve/Reject→Disburse Funds.
- Activity Diagram:
Common Mistakes to Avoid
Confusing Aggregation/Composition:
- Aggregation:
Departmentcan exist withoutUniversity(weak link). - Composition:
Carcannot exist withoutEngine(strong link). - Exam Pitfall: Drawing a hollow diamond for
Car↔Engine(wrong!).
- Aggregation:
Missing Stereotypes in Use Cases:
- Always label
<<includes>>and<<extends>>correctly. - Example:
Checkout<<includes>>Payment(mandatory), butApply Discount<<extends>>Checkout(optional).
- Always label
Incorrect State Transitions:
- Every arrow must have an event/guard condition.
- Wrong:
Order Placed → Shipped(missing trigger likeon Payment Success).
Overcomplicating Sequence Diagrams:
- Stick to one scenario per diagram.
- Bad: Combining
Login+Place Orderin one diagram.
Exam Tip
How This Unit is Tested
Diagram Drawing (30-40%):
- Class Diagram: Given a scenario (e.g., "Design a library system"), draw classes with correct relationships (aggregation vs. composition).
- Use Case Diagram: Identify actors and use cases from a user story (e.g., "As a customer, I want to return an item").
- State Machine: Draw transitions for a given lifecycle (e.g., "Order processing states").
Scenario Analysis (25-30%):
- Short-answer: "Explain how a sequence diagram differs from an activity diagram."
- True/False: "Aggregation implies strong ownership." (False!)
Real-World Application (20-25%):
- Case Study: "Model the workflow of a food delivery app (e.g., Foodmandu) using an activity diagram."
- Comparison: "Compare inheritance and association with examples from Daraz or eSewa."
Error Spotting (15-20%):
- Given a faulty diagram, identify 3 mistakes (e.g., wrong arrow type, missing guard condition).
Marks Distribution (Typical)
| Question Type | Marks | Focus Area |
|---|---|---|
| Draw a class diagram | 10 | Relationships, attributes, methods |
| Use case diagram from text | 8 | Actors, use cases, includes/extends |
| State machine for a system | 10 | States, transitions, events |
| Sequence diagram trace | 7 | Messages, lifelines, activation |
| Compare two diagrams | 5 | Activity vs. state machine |
Top 3 Exam Strategies
Memorize Symbols:
- Create a cheat sheet for UML symbols (e.g., hollow diamond = aggregation).
- Pro Tip: Use color-coding (e.g., red for composition, blue for association).
Practice with Real Scenarios:
- Model eSewa, Daraz, or Pathao workflows in all 5 diagrams.
- Example: For Khalti payment, draw:
- Class diagram (
User,Transaction,Bank). - Use case diagram (
Pay,Transfer,Check Balance). - Sequence diagram (
User→Khalti→Bank).
- Class diagram (
Time Management:
- Diagram questions: Spend 1.5–2 minutes per diagram (sketch first, refine later).
- Short answers: Allocate 30 seconds per point (e.g., "Define aggregation").
Based on the PU BE Computer (PU) syllabus for Software Engineering (CMP348), unit 4.
Discussion
Loading…