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.

Class DiagramComponent DiagramDeployment DiagramStructuralUse Case DiagramSequence DiagramActivity DiagramState Machine DiagramBehavioralUML Diagrams
Classification of UML diagrams (focus on the 5 key ones)

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()).
  • 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).

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 : contains

Real-World Tie:

  • When you add items to your Daraz cart, the system uses a composition relationship (Order owns Product instances).
  • If you cancel an order, the Order class’s cancel() method triggers updates in the Customer and Product classes.

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).

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:
    1. User selects Pay Bill (use case).
    2. The system includes Transfer Money (deducts from your wallet).
    3. 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 rejects

Real-World Tie:

  • When you book a Pathao ride, your order goes through these states:
    1. Waiting → RideAssigned (driver picks up).
    2. If the driver rejects, it loops back to Waiting.
    3. 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:
    1. The system checks Is Wallet Balanced?.
    2. If No, it forks to bank payment (parallel to SMS confirmation).
    3. Both paths merge at Send Confirmation SMS.

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:
    1. Your BrokerApp sends placeOrder() to NepseServer.
    2. NepseServer validates and executes the trade.
    3. The app shows TradeConfirmed to you.

Key Patterns in Sequence Diagrams

  1. Synchronous Call: Solid arrow (waits for response).
  2. Asynchronous Call: Sticky arrow (no wait).
  3. Loop: loop keyword (e.g., loop until stock available).
  4. Alternative: alt/else (e.g., alt success else failure).

In the Real World

  1. eSewa (Nepal)

    • Use Case Diagram: Models Pay Bill, Transfer Money, and Check Balance for users.
    • State Machine: Tracks Payment Initiated → Processing → Completed/Failed.
  2. Daraz (Nepal)

    • Class Diagram: Customer (places Order), Order (contains Product), Cart (aggregates Product).
    • Activity Diagram: Shows Add to Cart → Checkout → Payment → Ship Order workflow.
  3. Google Maps (Global)

    • Sequence Diagram: User → Google Maps → GPS Server → Route Calculation → Display Route.
    • State Machine: Navigation states: Route Planned → In Progress → Arrived.
  4. Ncell Recharge

    • Use Case: Customer → Recharge <<includes>> Payment <<extends>> Send Receipt.
  5. Bank Loan Processing (Global)

    • Activity Diagram: Apply Loan → Check Credit Score (decision) → Approve/Reject → Disburse Funds.

Common Mistakes to Avoid

  1. Confusing Aggregation/Composition:

    • Aggregation: Department can exist without University (weak link).
    • Composition: Car cannot exist without Engine (strong link).
    • Exam Pitfall: Drawing a hollow diamond for Car ↔ Engine (wrong!).
  2. Missing Stereotypes in Use Cases:

    • Always label <<includes>> and <<extends>> correctly.
    • Example: Checkout <<includes>> Payment (mandatory), but Apply Discount <<extends>> Checkout (optional).
  3. Incorrect State Transitions:

    • Every arrow must have an event/guard condition.
    • Wrong: Order Placed → Shipped (missing trigger like on Payment Success).
  4. Overcomplicating Sequence Diagrams:

    • Stick to one scenario per diagram.
    • Bad: Combining Login + Place Order in one diagram.

Exam Tip

How This Unit is Tested

  1. 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").
  2. Scenario Analysis (25-30%):

    • Short-answer: "Explain how a sequence diagram differs from an activity diagram."
    • True/False: "Aggregation implies strong ownership." (False!)
  3. 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."
  4. 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

  1. 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).
  2. 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).
  3. 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…