Skip to content
Tutorials Center
My learning

Topics

Lesson 2 of 57 ยท Getting Started with Design

Reading and Drawing UML for Low-Level Design

Read and draw UML class diagrams and sequence diagrams for low-level design: relationships, multiplicity, visibility and Mermaid syntax, with runnable examples.

Design patterns are usually explained with pictures, and the pictures are almost always UML (Unified Modeling Language) diagrams. You do not need all of UML. For low-level design (LLD) two diagram types cover nearly everything: the class diagram, which shows what exists and how it is related, and the sequence diagram, which shows who calls whom over time.

In an interview or a design review you will often sketch these on a whiteboard in under a minute. The goal is not a perfect standard-compliant drawing. It is a clear picture that others can read and challenge. This lesson teaches the symbols you actually need and the text-based Mermaid syntax that this site (and many code hosts) can render from plain text.

UML diagrams are drawings, so they are read-only here. The runnable example is a JavaScript stand-in: a tiny model of classes and relationships that prints the same facts a class diagram shows. It is not a UML tool.

Two diagrams do most of the work

Class diagram What exists and how it is connected.
Sequence diagram Who calls whom, in what order.
1 / 3

Anatomy of a class box

A class is drawn as a rectangle with three compartments: name, attributes, operations.

classDiagram
    class Account {
        -String id
        -double balance
        +deposit(double amount) void
        +withdraw(double amount) boolean
        +getBalance() double
    }

One class: name on top, fields in the middle, methods at the bottom.

The symbol before each member is its visibility:

Symbol Meaning Typical use
+ public operations other classes may call
- private fields and helper methods
# protected members for subclasses
~ package members visible within one package

Italic names (or the label <<abstract>>) mark abstract classes, and <<interface>> marks an interface. Underlined or $-marked members are static. Keep the boxes small: show only members that matter for the point you are making.

The six relationships

This is the part to memorize. Each relationship has a different line style, and each says something different about lifetime and knowledge.

Association

A plain line (or an arrow) means one class holds a reference to another and uses it over time. A Customer places Orders. The arrow shows who knows whom.

Aggregation

A hollow diamond on the "whole" side means has-a, where the parts can exist without the whole. A Team has Players, but a player still exists if the team is dissolved.

Composition

A filled diamond means owns-a, where the parts cannot meaningfully outlive the whole. An Order owns its OrderLines: delete the order and the lines go with it.

Dependency

A dashed arrow means one class uses another only briefly, for example as a method parameter or a local variable. It is the weakest link and the cheapest to change.

Inheritance (generalization)

A solid line with a hollow triangle pointing at the parent means is-a. SavingsAccount is an Account.

Realization

A dashed line with a hollow triangle pointing at an interface means a class implements it. CreditCard implements PaymentMethod.

Here are all six in one diagram.

classDiagram
    class PaymentMethod {
        <<interface>>
        +pay(double amount) boolean
    }
    class CreditCard
    class Customer
    class Order
    class OrderLine
    class Team
    class Player
    class Receipt
    class Account
    class SavingsAccount

    PaymentMethod <|.. CreditCard : realization
    Account <|-- SavingsAccount : inheritance
    Customer "1" --> "0..*" Order : association
    Order "1" *-- "1..*" OrderLine : composition
    Team "1" o-- "0..*" Player : aggregation
    Order ..> Receipt : dependency

Relationship arrows in Mermaid: <|.. realization, <|-- inheritance, --> association, *-- composition, o-- aggregation, ..> dependency.

The aggregation versus composition choice is where people argue. A practical test: if I delete the whole, should the parts be deleted too? If yes, use composition; if the parts are shared or live elsewhere, use aggregation (or simply association). When in doubt, use a plain association. Many experienced designers skip the hollow diamond completely because it adds little.

Multiplicity

The numbers near the ends of a line say how many objects take part.

Notation Meaning
1 exactly one
0..1 zero or one (optional)
* or 0..* zero or more
1..* one or more
2..5 between two and five

In the diagram above, a Customer has zero or more orders, and an Order has at least one line. Multiplicities turn directly into code decisions: 1..* suggests a non-empty collection and a validation rule, while 0..1 suggests a nullable field or an optional type.

Turning a diagram into code

The mapping from UML to code is mostly mechanical. Inheritance is extends, realization is implements, and an association with multiplicity 0..* is a collection field. This is the Java reading of the composition and inheritance lines above (read-only):

Java
interface PaymentMethod { boolean pay(double amount); }

class CreditCard implements PaymentMethod {          // realization
    public boolean pay(double amount) { return true; }
}

class Order {
    private final List<OrderLine> lines = new ArrayList<>();  // composition: Order owns the lines
    void add(OrderLine line) { lines.add(line); }
    Receipt receipt() { return new Receipt(this); }           // dependency: used briefly
}

In C++, composition is often a plain member or a std::vector<OrderLine> by value, because the parts then live and die with the owner. Aggregation is typically a pointer or reference to an object that someone else owns. The language itself can make the lifetime difference visible, which is why composition is easy to see in C++ and harder to see in Java or Python, where everything is a reference.

Sequence diagrams

A class diagram is static. A sequence diagram shows one scenario over time. Participants sit across the top, each with a vertical lifeline, and horizontal arrows are messages read from top to bottom. A solid arrow is a call, a dashed arrow a return.

sequenceDiagram
    participant C as Client
    participant O as Order
    participant P as PaymentMethod
    C->>O: checkout()
    O->>P: pay(total)
    P-->>O: true
    O-->>C: receipt

A checkout scenario: the client calls the order, the order calls the payment method and passes the result back.

Use a sequence diagram when the order of calls is the point: observer notifications, a chain of handlers, a request through layers. Use a class diagram when the structure is the point. Patterns usually come with both, and interviews like to see you draw both.

Drawing tips for whiteboards

  1. Start with the nouns from the requirements as boxes, then add verbs as methods.
  2. Draw only the relationships that matter for the question. A diagram with thirty arrows teaches nothing.
  3. Put interfaces and abstract classes at the top, concrete classes below them, so inheritance arrows point upward.
  4. Label every non-obvious association with a verb ("places", "contains").
  5. Add multiplicities on the lines that drive decisions, not everywhere.

A model that prints its own relationships

To see how a class diagram holds information you can query, here is a stand-in: a small JavaScript model of classes and relationships that prints the same facts the picture shows, and checks which classes sit under an interface.

JS A tiny class model

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

No output.

Sequence diagrams have a text form too. This second stand-in records calls as a program runs and prints them in the style of a sequence diagram, which is a handy way to check that your code does what your drawing says.

JS Tracing calls like a sequence diagram

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

No output.

Behavioral and structural diagrams beyond class and sequence

Class and sequence diagrams cover most low-level design interviews, but UML 2 defines more. Four of them are worth knowing: state, activity, use-case and component diagrams. Each answers a different question, and each can be drawn with the diagram fences used on this site.

Diagram Question it answers Best for
Use-case What can each kind of user do with the system? Requirements, scope, the first meeting
Activity In what order do steps, decisions and parallel branches happen? Workflows, algorithms, business processes
State What states can one object be in, and what moves it between them? Orders, tickets, vending machines, protocols
Component What are the big deployable parts and what do they depend on? Architecture overviews, module boundaries

Use-case diagram

A use-case diagram shows actors (people or other systems outside the boundary) and the use cases (goals) they can achieve. It deliberately leaves out how. Draw a box for the system boundary, ovals for use cases and a line from each actor to the goals it takes part in. Two relationships appear often: include (a use case always uses another, such as "Place order" includes "Pay") and extend (an optional addition, such as "Apply coupon").

flowchart LR
    Customer(["Customer"])
    Admin(["Admin"])
    subgraph Shop["Online shop"]
        Browse(["Browse products"])
        Place(["Place order"])
        Pay(["Pay"])
        Coupon(["Apply coupon"])
        Manage(["Manage catalog"])
    end
    Customer --- Browse
    Customer --- Place
    Admin --- Manage
    Place -. "include" .-> Pay
    Coupon -. "extend" .-> Place

Actors sit outside the system boundary; ovals are goals. A dashed arrow labeled include means "always uses", and extend means "optionally adds to".

(Mermaid has no dedicated use-case syntax, so this uses a flowchart with rounded shapes. On paper, actors are stick figures and use cases are ovals.)

Activity diagram

An activity diagram is a flowchart with extras: a start and end, decisions (diamonds with guard conditions) and fork/join bars for steps that happen in parallel. Use it to explain a process before writing any class.

flowchart TD
    Start(("Start")) --> Receive["Receive order"]
    Receive --> Stock{"In stock?"}
    Stock -- "no" --> Backorder["Create back-order"] --> End
    Stock -- "yes" --> Fork["Fork: do in parallel"]
    Fork --> Pack["Pack items"]
    Fork --> Charge["Charge card"]
    Pack --> Join["Join: both done"]
    Charge --> Join
    Join --> Ship["Ship order"] --> End(("End"))

Packing and charging happen in parallel after the fork; shipping waits at the join until both finish.

State diagram

A state diagram (state machine) follows one object through its life. Draw states as rounded boxes, transitions as arrows labeled event [guard] / action, a filled dot for the start and a bullseye for the end. It is the direct picture of the State pattern.

stateDiagram-v2
    [*] --> Placed
    Placed --> Paid: pay [amount ok]
    Placed --> Cancelled: cancel
    Paid --> Shipped: ship
    Paid --> Cancelled: cancel / refund
    Shipped --> Delivered: deliver
    Delivered --> [*]
    Cancelled --> [*]

An order can be cancelled before it ships, with a refund if it was already paid; once shipped it can only be delivered.

A state diagram is also a specification you can test. The table of allowed transitions below is the same information as the picture, and the code rejects any move the diagram does not draw.

JS Turning a state diagram into code

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

No output.

Component diagram

A component diagram zooms out: boxes are replaceable parts of the system (a web app, an order service, a payment adapter, a database), with provided interfaces (the lollipop, what a component offers) and required interfaces (the socket, what it needs). It shows dependencies at the level of modules, which is where the Dependency Inversion Principle is easiest to see: arrows should point toward stable abstractions.

flowchart LR
    subgraph Web["Web app"]
        UI["UI"]
    end
    subgraph Orders["Order service"]
        OS["Order logic"]
    end
    subgraph Pay["Payment adapter"]
        PA["Gateway client"]
    end
    DB[("Database")]
    UI -->|"uses OrderAPI"| OS
    OS -->|"requires PaymentPort"| PA
    OS -->|"reads and writes"| DB

Each box is a replaceable component; arrows show which one requires something from another.

Object diagram

A class diagram describes what could exist; an object diagram is a snapshot of what does exist at one moment. Each box is an instance, written name : Class and underlined in strict UML, with concrete attribute values. Use it to explain a tricky structure with real data, for example "this order holds these two items", or to check that your class diagram allows the situation you have in mind.

classDiagram
    class order42["order42 : Order"] {
        status = PAID
    }
    class itemA["itemA : OrderItem"] {
        sku = pen
        qty = 3
    }
    class itemB["itemB : OrderItem"] {
        sku = ink
        qty = 1
    }
    order42 --> itemA
    order42 --> itemB

A snapshot: one order object linked to two item objects.

Package diagram

When a system has dozens of classes, a package diagram groups them into packages (folders, modules, namespaces) and shows only the dependencies between those groups. A dashed arrow from checkout to payments means "something in checkout uses something in payments". It is the quickest way to check that dependencies point in one direction, and to spot a cycle between packages, which is a sign of poor layering.

Deployment diagram

A deployment diagram shows where software runs: boxes (nodes) for servers, containers or devices, with the artifacts deployed on them and the connections between them, such as "web app container talks to database server over TCP". It is more of an architecture tool than a low-level one, but it is the right diagram when the question is "what runs where".

Swimlanes in activity diagrams

An activity diagram can be divided into swimlanes, vertical or horizontal bands that each belong to one actor or component, for example Customer, Web shop and Warehouse. Every action sits in the lane of whoever performs it, and arrows crossing a lane boundary are hand-overs. Swimlanes answer "who does this step?", which a plain flowchart cannot show. Activity diagrams also help to clarify complex logic with branches and parallel paths (fork and join bars) before you write any code.

Parameter direction and navigability

Two small details make class diagrams more precise.

  • Parameter direction. A parameter can be marked in (the method only reads it, the default), out (the method sets it for the caller) or inout (it reads the value and changes it). Example: parse(in text: String, out result: Node). Most modern languages return values instead of using out parameters, so you will mostly see this in C, C++ and C# (out, ref) code, but the notation tells a reader who may change what.
  • Directed association (navigability). A plain line means "these classes know each other". An arrow, Order --> Customer, means only Order holds a reference to Customer; Customer does not know its orders. Drawing the arrow forces a useful decision: which side needs to find the other? One-way references keep coupling low and are easier to keep consistent.

Sequence diagrams: what to watch out for

Sequence diagrams are easy to read for one scenario and hard to scale. They get crowded quickly when there are many participants, they show a single path rather than all the paths (alternatives use alt and opt frames, loops use loop), and concurrency, parallel threads and real-time deadlines are awkward to express. The same sequence diagram is useful for three jobs: visualizing dynamic behavior before coding, documenting how a feature works for the next maintainer, and following a request through the system when you debug a failure. Keep each diagram to one scenario and fewer than about six lifelines.

UML tools

You do not need special software. Whiteboards, paper and text-based tools like Mermaid or PlantUML are enough for design work, and text diagrams live in the repository next to the code, so review and version history come for free. Graphical editors such as Lucidchart, Visual Paradigm and StarUML help when you need polished diagrams for documentation. Whatever you use, the purpose is the same: better communication and planning before and during development.

Choosing the right diagram

  • Starting a project: use-case, then activity for the key workflows.
  • Designing classes: class diagram for structure, sequence for one scenario, state for any object with a life cycle.
  • Explaining the architecture to a new teammate: component diagram, then deployment diagram if infrastructure matters.
  • In an interview: say which diagram you are drawing and why; one clear class diagram plus a state diagram for the one tricky object is usually enough.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A Library has Books, but a Book can still exist if the Library closes. Which relationship fits best?

    The parts outlive the whole, which is aggregation (a hollow diamond). With composition the parts would be deleted along with the whole.
  2. 2. Which line style means a class implements an interface?

    Realization is a dashed line with a hollow triangle at the interface. A solid line with a hollow triangle is inheritance.
  3. 3. What does the multiplicity 1..* on the OrderLine end of a line mean?

    1..* means at least one and possibly many, so an order must have at least one line.
  4. 4. When is a sequence diagram a better choice than a class diagram?

    Sequence diagrams show messages over time in a single scenario. Class diagrams show static structure.

Summary

  • Class diagrams show structure; sequence diagrams show one scenario in time order.
  • A class box has a name, attributes and operations, with visibility marked by +, -, # and ~.
  • The six relationships are association, aggregation, composition, dependency, inheritance and realization, ordered roughly from weak to strong coupling for the first four.
  • Composition means the parts die with the whole; aggregation means they live on alone.
  • Multiplicities such as 0..1 and 1..* map straight to optional fields and collections.
  • Mermaid lets you keep diagrams as text next to the code.

Next, refresh the object-oriented ideas those diagrams depend on: OOP Foundations for Design.