UML for Interviews: Class, Sequence, State & Activity Diagrams
UML has fourteen diagram types and a specification of several hundred pages. A low-level design interview uses four of them, and for most of the round only one. Nobody is grading you on whether your arrowheads match section 11.5.4 of the OMG standard. What's being judged is whether the picture helps you and the interviewer think about the same design, and whether it's correct: an ownership diamond that says the wrong thing about lifetimes, or a multiplicity that quietly makes a many-to-many relationship one-to-many, is a design mistake that happens to show up in a drawing.
This page is the working guide. It covers which diagram answers which question, how long each deserves in a time-boxed round, the notation you actually need and what it means, and how to write it in Mermaid, which is the format this site uses and the one most online interview editors can render. One running example, a parcel-locker system, goes through all four diagrams so you can see how they check each other.
Key Takeaway
Draw a class diagram to show structure, a sequence diagram to prove one flow works, a state diagram for any entity whose rules depend on its status, and an activity diagram only when a process branches enough that prose gets confusing. Each diagram should answer a question you or the interviewer actually has. If it doesn't, skip it and spend the minutes on code.
What this page builds on. Object-Oriented Programming covers the concepts (encapsulation, inheritance, composition, interfaces), and OOP Concepts in Depth & UML Class Diagrams introduces the basic class-diagram symbols, two worked models, sequence and use-case diagrams. This page doesn't repeat those introductions. It goes further on the parts interviews probe, adds state and activity diagrams, and is strict about where Mermaid's notation and UML's disagree.
1. Why draw anything at all?
Diagrams in an LLD round do three jobs.
- They make a shared object to point at. Talking through eight classes without a picture forces the interviewer to hold your design in their head. With a picture, "this arrow here" replaces two sentences, and the interviewer can interrupt with "what owns the compartment?" before you've written fifty lines of code around the wrong answer.
- They catch design errors cheaply. Drawing a multiplicity forces a decision. Is a parking ticket for one spot or many? Can a member have two active loans for the same book? A wrong answer costs ten seconds to fix on the board and ten minutes to fix in code.
- They show the interviewer how you think. Starting with boxes and relationships before attributes, putting interfaces where requirements say "different kinds of", and walking one use case through the picture are signals interviewers look for. The LLD interview framework covers the full timeline these steps sit in.
What a diagram doesn't do is earn points by itself. A beautiful diagram with no code behind it scores worse than a rough one with working classes. Treat every diagram as a means to code you can defend, not the deliverable.
The over-drawing trap
A common way to fail an LLD round is to spend 25 minutes perfecting a class diagram with every getter, then run out of time before the interesting part: the allocation logic, the state transitions, the concurrency. Draw the minimum that makes the design clear, then move on. You can add detail to the diagram later when the code shows you need it.
2. Which diagram answers which question
Each diagram type answers one kind of question well and is useless for the others. Pick the diagram from the question you need to answer.
| Question you need answered | Diagram | What it can't tell you |
|---|---|---|
| What are the classes, what does each hold, and who owns whom? | Class | The order things happen in, or what happens at runtime |
| Does this flow actually work with these classes? Who calls whom, in what order? | Sequence | Other scenarios: each sequence diagram is a single scenario |
| What statuses can this object be in, and which events are legal in each? | State | How other objects collaborate to cause the events |
| What are the steps, decisions and parallel branches of this process, and who does each? | Activity | Which classes exist, and object lifetimes |
| Which actors use the system for which goals? | Use-case | Almost everything about the design (it's a scope tool) |
| What does memory look like at one moment? | Object | Anything general, since it's a snapshot of one case |
A quick way to choose in the moment:
flowchart TD
Q["What am I trying to show?"] --> S1{"Structure: what exists<br/>and who owns what?"}
S1 -->|"yes"| CD["Class diagram"]
S1 -->|"no"| S2{"One flow across<br/>several objects?"}
S2 -->|"yes"| SD["Sequence diagram"]
S2 -->|"no"| S3{"One object whose rules<br/>depend on its status?"}
S3 -->|"yes"| ST["State diagram"]
S3 -->|"no"| S4{"A process with many<br/>branches or actors?"}
S4 -->|"yes"| AD["Activity diagram / flowchart"]
S4 -->|"no"| TALK["Say it in a sentence and keep going"]
The last box matters. Many things in an interview are better said than drawn. "Payments go through a PaymentGateway interface with a fake for tests" needs no picture.
When to draw what in a 45-minute round
Here's a typical allocation for a whiteboard or online-editor LLD round. The LLD interview framework has the full timeline; this table only shows where diagrams fit.
| Minutes | Phase | Diagram work | Time on diagrams |
|---|---|---|---|
| 0–5 | Clarify requirements, agree scope | None, or a three-line actor list. Use-case diagrams are rarely worth drawing; say the use cases aloud. | 0–1 |
| 5–10 | Identify entities | Boxes with names only, plus the core relationships and multiplicities | 3–4 |
| 10–18 | Class diagram | Add key attributes, public operations, interfaces, enums | 5–7 |
| 18–22 | Walk the hardest flow | One sequence diagram, or a verbal walk-through pointing at the class diagram | 3–4 |
| 22–24 | Lifecycle entity, if there is one | A state diagram for the one entity with three or more statuses | 2–3 |
| 24–40 | Code the core | Update the class diagram if the code changes it | 1 |
| 40–45 | Extensions, concurrency | Sketch only the changed part of the diagram | 1–2 |
Roughly 15 minutes of a 45-minute round go to diagrams, and most of that is the class diagram. In a 90-minute machine-coding round you usually draw less, often just a quick class sketch before coding, because the deliverable is running code.
When to draw an activity diagram: rarely, and only when the interviewer asks "walk me through the algorithm" for something with real branching (elevator dispatch, the order of validation checks in a payment, a retry and escalation policy). A short flowchart beats a paragraph there.
Typed versus whiteboard
Online interviews increasingly happen in a shared editor, sometimes one that renders Mermaid or PlantUML, sometimes plain text. On a whiteboard, speed comes from drawing boxes with names only, then adding members in a second pass. In text, the same discipline applies: write the relationships first.
LockerStation *-- Compartment (1 to 1..*)
Delivery --> Compartment (0..1)
LockerService --> AllocationStrategy <<interface>>
Three lines like these, typed in the first ten minutes, communicate more than a half-finished picture.
3. The running example: a parcel locker
Here's the problem we'll use throughout. It's written for this page.
Parcel lockers. A delivery company runs locker stations in supermarkets and train stations. Each station has compartments in three sizes: small, medium and large. A courier arrives with a parcel, scans it at the station's kiosk, and the system picks a free compartment that fits, preferring the smallest one. The door unlocks; the courier puts the parcel in and closes the door. The recipient then gets a text message with a six-digit pickup code. The recipient has 72 hours to collect, and gets a reminder after 48. At the kiosk they type the code; the right code opens the door. Five wrong codes in a row block that delivery for 15 minutes. Parcels not collected in 72 hours expire, and a courier takes them back to the depot. If the courier doesn't close the door within five minutes of it opening, the deposit is cancelled and the compartment freed. Messages may go by SMS or email, and the company plans to add app push notifications.
Requirements we take from it:
- Functional: deposit, notify, pick up with a code, lockout after failed attempts, reminders, expiry, return to depot, cancelled deposits.
- Non-functional: a code must never open the wrong compartment; two couriers at the same station must never get the same compartment; notification channels must be pluggable.
This example has enough structure for a class diagram, a flow with asynchronous hardware events for a sequence diagram, a lifecycle with timers for a state diagram, and a branching kiosk process for an activity diagram.
4. Class diagrams, done properly
4.1 The class box
UML draws a class as a box with up to three compartments: name, attributes, operations. The full UML text syntax for members is:
attribute: visibility name : Type [multiplicity] = default
operation: visibility name(param : Type, ...) : ReturnType
So in strict UML, a compartment's attribute looks like - expiresAt : Instant and an operation like + verify(code : String, now : Instant) : Boolean. Mermaid's class diagrams accept a more Java-like order, type then name, with the return type after the parentheses separated by a space:
classDiagram
class Delivery {
-TrackingId trackingId
-Size size
-DeliveryState state
-Instant expiresAt
-int failedAttempts
+assign(Compartment c) void
+deposit(Instant now) PickupCode
+verify(String code, Instant now) bool
+markPickedUp(Instant now) void
}
Mermaid renders member text more or less as you write it, so you can also write UML-order members like -expiresAt : Instant. Pick one style and keep it for the whole diagram. Mixing int count and name : String in one diagram looks careless.
What to show in an interview. Show attributes that drive behaviour (status, capacity, expiry, failed attempts) and public operations that other classes call. Leave out getters, setters, toString, constructors unless they enforce something interesting, and private helpers. A box with eight well-chosen members tells the interviewer more than one with twenty-five.
4.2 Visibility
| Symbol | UML meaning | Java | Python convention | TypeScript |
|---|---|---|---|---|
+ | public | public | plain name | public (the default) |
- | private | private | _name (by convention) | private or #name |
# | protected | protected | _name (no real equivalent) | protected |
~ | package | no modifier | module-level, not exported | not exported from the module |
Two points matter in interviews. First, mark state as private (-) unless there's a reason not to. A diagram full of public attributes signals an anaemic design where any caller can change any field. Second, don't spend time on # and ~ unless the design depends on them, such as a template method whose hook is protected (see Notifier.send below).
4.3 Static, abstract, interfaces and enums
| Concept | UML | Mermaid |
|---|---|---|
| Static member | Underlined | $ suffix: +nextId()$ String, +int count$ |
| Abstract operation | Italic name | * suffix: #send(String msg)* void |
| Abstract class | Italic class name, or {abstract} | Annotation <<abstract>> |
| Interface | «interface» stereotype, or the lollipop circle | Annotation <<interface>> |
| Enumeration | «enumeration» with literals in the attribute compartment | Annotation <<enumeration>>, literals listed as members |
| Any other stereotype | «stereotype» | Any text: <<value object>>, <<service>> |
classDiagram
class AllocationStrategy {
<<interface>>
+choose(List~Compartment~ candidates, Size size) Compartment
}
class Notifier {
<<abstract>>
+notifyReady(Recipient r, PickupCode code) void
#send(Recipient r, String message)* void
}
class Size {
<<enumeration>>
SMALL
MEDIUM
LARGE
}
class PickupCode {
<<value object>>
-String hash
+generate()$ PickupCode
+matches(String attempt) bool
}
Interface or abstract class? In a diagram, the choice tells the reader something. An interface says "here's a contract with no shared implementation; anything can fulfil it". An abstract class says "subclasses share this code and this fixed sequence of steps". Notifier is abstract here because every channel formats the message the same way and differs only in send; that's the Template Method pattern. AllocationStrategy is an interface because smallest-fit, nearest-to-the-kiosk and balanced-wear share nothing. The mechanics of abstract classes versus interfaces are covered in the earlier lesson; here the question is just what each box tells the reader.
Enums in diagrams. Draw an enum box when the values carry meaning the reader needs (sizes, statuses), and connect it to the classes that use it with a plain association. Don't draw an enum for something with two values that's really a boolean. When a status enum has more than about three values, that's usually a sign the owning entity also deserves a state diagram (section 6).
4.4 Relationships, from weakest to strongest
Relationships are where diagrams go wrong most often. Here they are in order of how tightly they bind two classes, with the code that tells you which one you're looking at.
Dependency: "uses, briefly"
A dashed arrow with an open head. A depends on B if B appears only in a method's parameter, local variable or return type, with no field. If B changes, A might have to change, but A doesn't hold on to a B.
classDiagram
LockerService ..> Clock : reads time
Code tell: deposit(..., Clock clock) takes it as a parameter. Draw dependencies sparingly. Every class depends on dozens of things, and a diagram that shows them all hides the important lines. Show dependencies on things that matter to the design: a Clock (because time is a testing seam), a PaymentGateway passed per call, a factory.
Association: "knows about, structurally"
A solid line. A holds a reference to B as part of its state, usually a field. An open arrowhead shows navigability: Delivery --> Compartment means a delivery knows its compartment, and the compartment doesn't know the delivery. A line with no arrowheads, A -- B, says either "both directions" or "not decided yet", so be explicit when it matters.
classDiagram
Delivery --> "0..1" Compartment : stored in
Code tell: a field. Multiplicity 0..1 means the field can be empty (a delivery has no compartment until it's assigned), so in code it's nullable or an Optional. Bidirectional associations double the work of keeping both sides consistent; draw one only when both sides really need to navigate, and be ready to say who updates both ends.
Aggregation: "has, but doesn't own"
A hollow diamond at the whole. The parts can exist without the whole and may be shared between wholes. LockerService o-- LockerStation: the service manages stations, but stations exist independently, and an operations dashboard might hold the same stations.
UML 2 calls aggregation's semantics deliberately loose, and many teams just draw association instead. In an interview, use aggregation only when you can say what it adds ("the stations outlive the service, which only coordinates them"). If you can't, a plain arrow is clearer.
Composition: "owns, and the part dies with it"
A filled diamond at the whole. The part belongs to exactly one whole at a time, is usually created by the whole, and its lifetime ends with the whole's. LockerStation *-- Compartment: compartments are built into the station; a compartment can't sit in two stations; demolish the station and its compartments go too.
classDiagram
LockerStation "1" *-- "1..*" Compartment : contains
Code tell: the whole creates the parts inside itself and never hands out a way to swap them. Composition matters more than any other relationship in LLD, because composition chains mark aggregate boundaries (the cluster of objects that change together under one root's rules). From Nouns to Classes builds on this.
Generalization: "is a"
A solid line with a hollow triangle at the parent. Notifier <|-- SmsNotifier. In code: extends. Use it for stable families where the subtype really can stand in for the parent (Liskov substitution), and be ready to explain why you didn't use composition.
Realization: "implements"
A dashed line with a hollow triangle at the interface. AllocationStrategy <|.. SmallestFit. In code: implements, or in Python, subclassing an ABC or matching a Protocol.
Summary
| Relationship | Line | Head | Mermaid | Typical code | Lifetime link |
|---|---|---|---|---|---|
| Dependency | dashed | open arrow | A ..> B | parameter, local, return type | none |
| Association | solid | open arrow (navigable end) | A --> B | field | none |
| Aggregation | solid | hollow diamond at whole | Whole o-- Part | field holding parts created elsewhere | none |
| Composition | solid | filled diamond at whole | Whole *-- Part | whole creates and keeps parts | part ends with the whole |
| Generalization | solid | hollow triangle at parent | Parent <|-- Child | extends | n/a |
| Realization | dashed | hollow triangle at interface | Iface <|.. Impl | implements | n/a |
Reading Mermaid arrows
In Mermaid, the symbol sits at the end where you type it. Parent <|-- Child puts the triangle at Parent. Whole *-- Part puts the diamond at Whole. You can flip them (Child --|> Parent, Part --* Whole) and they render the same, but keep one direction for the whole diagram. Writing parents and wholes on the left is easier to scan.
4.5 Multiplicity, read properly
Multiplicity sits at the far end of the line from the class it constrains. LockerStation "1" *-- "1..*" Compartment reads in two directions:
- a station has one or more compartments (read left to right, using the number next to
Compartment); - a compartment belongs to exactly one station (read right to left, using the number next to
LockerStation).
Every multiplicity is a decision with consequences in code.
| Multiplicity | In code | Question it forces |
|---|---|---|
1 | required constructor argument, never null | Can this ever be missing, even briefly during creation? |
0..1 | nullable field or Optional | What does the object do while it's empty? |
* / 0..* | collection, may be empty | Is an empty collection valid, or should it be 1..*? |
1..* | collection validated non-empty | Who stops the last one being removed? |
m..n (e.g. 2..4) | collection with a size check | Is this a real rule or a guess? |
The relationship that most often goes wrong is a hidden many-to-many. If a Student takes many Courses and a Course has many Students, and the relationship has data of its own (a grade, an enrolment date), UML draws an association class hanging off the line by a dashed connector. Mermaid has no association class, so promote it to a real class with two one-to-many links, which is also how you'll implement it:
classDiagram
class Enrolment {
-LocalDate enrolledOn
-Grade grade
}
Student "1" --> "0..*" Enrolment
Course "1" --> "0..*" Enrolment
That middle class almost always turns out to matter. In a hotel it's the Reservation between Guest and Room; in a library it's the Loan between Member and BookCopy.
4.6 The parcel-locker class diagram
Putting it together:
classDiagram
direction LR
class LockerStation {
-String id
-String address
+freeCompartments(Size size) List~Compartment~
}
class Compartment {
-String id
-Size size
-bool free
+occupy() void
+release() void
}
class Size {
<<enumeration>>
SMALL
MEDIUM
LARGE
}
class Delivery {
-TrackingId trackingId
-Size size
-DeliveryState state
-Instant expiresAt
-int failedAttempts
+assign(Compartment c) void
+deposit(Instant now) PickupCode
+verify(String code, Instant now) bool
+markPickedUp(Instant now) void
}
class DeliveryState {
<<enumeration>>
CREATED
ASSIGNED
DEPOSITED
PICKED_UP
EXPIRED
RETURNED
CANCELLED
}
class PickupCode {
<<value object>>
-String hash
+matches(String attempt) bool
}
class LockerService {
+startDeposit(TrackingId id, Size size) Compartment
+confirmDeposit(TrackingId id) void
+pickUp(String stationId, String code) void
+expireOverdue() int
}
class AllocationStrategy {
<<interface>>
+choose(List~Compartment~ candidates, Size size) Compartment
}
class SmallestFit
class Notifier {
<<abstract>>
+notifyReady(Recipient r, PickupCode code) void
#send(Recipient r, String message)* void
}
class SmsNotifier
class EmailNotifier
class Clock {
<<interface>>
+instant() Instant
}
LockerStation "1" *-- "1..*" Compartment : contains
Compartment --> Size
Delivery --> Size
Delivery --> DeliveryState
Delivery --> "0..1" Compartment : stored in
Delivery *-- "0..1" PickupCode
LockerService o-- "1..*" LockerStation : manages
LockerService --> "*" Delivery : tracks
LockerService --> AllocationStrategy
LockerService --> Notifier
LockerService --> Clock
AllocationStrategy <|.. SmallestFit
Notifier <|-- SmsNotifier
Notifier <|-- EmailNotifier
Reading it as an interviewer would, in the order the earlier lesson recommends:
- Extension points first.
AllocationStrategy(interface) andNotifier(abstract) are where the requirements said "prefer the smallest" and "plans to add push". A new channel is one new subclass. - Ownership. Stations own compartments. A delivery owns its pickup code. Nothing else owns anything, so the composition chains are short and clear.
- Multiplicity. A delivery has at most one compartment, which prompts the obvious follow-up: what's the delivery doing while it has none? The state diagram in section 6 answers it.
- Time.
Clockis an interface held by the service, so tests can run expiry and lockout without waiting 72 hours.
Two things this diagram deliberately doesn't show: a DeliveryRepository (in-memory maps are enough for an interview, and you can say so) and the kiosk UI (outside the domain model).
4.7 From the diagram to code
Every line in the diagram should correspond to something you can point at in code. Here's a compact, runnable Java version of the core relationships, with each relationship labelled. It was compiled and run with java LockerModel.java on JDK 24.
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
enum Size { SMALL, MEDIUM, LARGE } // <<enumeration>>
class Compartment {
private final String id;
private final Size size;
private boolean free = true;
Compartment(String id, Size size) { this.id = id; this.size = size; }
String id() { return id; }
Size size() { return size; }
boolean isFree() { return free; }
void occupy() { free = false; }
void release() { free = true; }
}
class LockerStation {
private final String id;
// Composition: the station creates its compartments, nobody else holds them, they go when it goes.
private final List<Compartment> compartments = new ArrayList<>();
LockerStation(String id, int small, int medium, int large) {
this.id = id;
int n = 0;
for (int i = 0; i < small; i++) compartments.add(new Compartment(id + "-" + (++n), Size.SMALL));
for (int i = 0; i < medium; i++) compartments.add(new Compartment(id + "-" + (++n), Size.MEDIUM));
for (int i = 0; i < large; i++) compartments.add(new Compartment(id + "-" + (++n), Size.LARGE));
}
List<Compartment> compartments() { return Collections.unmodifiableList(compartments); }
}
interface AllocationStrategy { // <<interface>>
Optional<Compartment> choose(List<Compartment> candidates, Size parcelSize);
}
class SmallestFit implements AllocationStrategy { // realization
public Optional<Compartment> choose(List<Compartment> candidates, Size parcelSize) {
return candidates.stream()
.filter(c -> c.isFree() && c.size().compareTo(parcelSize) >= 0)
.min(Comparator.comparing(Compartment::size));
}
}
abstract class Notifier { // <<abstract>>
// Template method: the abstract class fixes the steps, subclasses fill in send().
final String notifyReady(String recipient, String code) {
String message = "Your parcel is ready. Code " + code;
send(recipient, message);
return message;
}
protected abstract void send(String recipient, String message);
}
class SmsNotifier extends Notifier { // generalization
final List<String> outbox = new ArrayList<>();
protected void send(String recipient, String message) { outbox.add(recipient + ": " + message); }
}
class Delivery {
private final String trackingId;
private final Size size;
private Compartment compartment; // association, 0..1
private Instant expiresAt;
Delivery(String trackingId, Size size) { this.trackingId = trackingId; this.size = size; }
Size size() { return size; }
Optional<Compartment> compartment() { return Optional.ofNullable(compartment); }
void depositInto(Compartment c, Instant expiresAt) { this.compartment = c; this.expiresAt = expiresAt; c.occupy(); }
Instant expiresAt() { return expiresAt; }
}
class LockerService {
static final Duration HOLD = Duration.ofHours(72);
private final AllocationStrategy strategy;
private final Notifier notifier;
LockerService(AllocationStrategy strategy, Notifier notifier) { this.strategy = strategy; this.notifier = notifier; }
// Dependency: Clock is only a parameter, so LockerService has no field of that type.
boolean deposit(LockerStation station, Delivery delivery, String recipient, Clock clock) {
Optional<Compartment> chosen = strategy.choose(station.compartments(), delivery.size());
if (chosen.isEmpty()) return false;
delivery.depositInto(chosen.get(), clock.instant().plus(HOLD));
notifier.notifyReady(recipient, "482913");
return true;
}
}
public class LockerModel {
public static void main(String[] args) {
LockerStation station = new LockerStation("ST1", 1, 1, 0);
SmsNotifier sms = new SmsNotifier();
LockerService service = new LockerService(new SmallestFit(), sms);
Clock clock = Clock.fixed(Instant.parse("2026-11-10T09:00:00Z"), ZoneOffset.UTC);
Delivery small = new Delivery("TRK-1", Size.SMALL);
Delivery medium = new Delivery("TRK-2", Size.MEDIUM);
Delivery another = new Delivery("TRK-3", Size.SMALL);
if (!service.deposit(station, small, "+15550100", clock)) throw new AssertionError();
if (!small.compartment().orElseThrow().id().equals("ST1-1")) throw new AssertionError("smallest fit");
if (!service.deposit(station, medium, "+15550101", clock)) throw new AssertionError();
if (service.deposit(station, another, "+15550102", clock)) throw new AssertionError("station is full");
if (!small.expiresAt().equals(Instant.parse("2026-11-13T09:00:00Z"))) throw new AssertionError();
if (sms.outbox.size() != 2) throw new AssertionError();
System.out.println("locker model checks passed");
}
}
Notice that the code version makes Clock a dependency (a parameter), while the full diagram shows it as an association (LockerService --> Clock, a field). Both are reasonable; what's not reasonable is a diagram that says one while the code does the other. When you change your mind while coding, fix the line on the diagram. Interviewers notice when the two drift apart.
4.8 Where Mermaid differs from UML
Mermaid's class diagrams cover the notation interviews need, but they aren't full UML. Know the gaps so you don't present a Mermaid limitation as a design decision.
| Topic | Standard UML | Mermaid classDiagram | What to do |
|---|---|---|---|
| Member order | name : Type, op(p : T) : R | Accepts Type name and op(T p) R; renders text largely as written | Pick one style per diagram |
| Static | Underlined | $ suffix | Use $ |
| Abstract | Italics | * suffix on operations, <<abstract>> on the class | Use both on abstract classes |
| Stereotypes | «name» with guillemets | <<name>>, any text | Fine |
| Role names | A name at each end of an association | One label in the middle (: label) | Put the role in the label: : stored in |
| Navigability "not navigable" | An x on the end | Not supported | Use an arrow on the navigable end only |
| Association class | A class attached to a line by a dashed connector | Not supported | Promote it to a class with two associations (section 4.5) |
| Qualified association | A small box at the end with the key | Not supported | Show a Map~K, V~-style field or say it aloud |
| N-ary association | A diamond joining three or more classes | Not supported | Promote to a class |
| Constraints | {ordered}, {unique}, OCL in braces | No constraint syntax | Use note for Class "text" |
| Templates (generics) | Dashed box on the class corner with T | ~T~: List~Compartment~ | See 4.9 |
| Packages | Tabbed folders, nestable | namespace Name { }, one level | Fine for grouping |
| Interface ball | Lollipop circle | Iface ()-- Impl lollipop syntax exists | <<interface>> plus <|.. is clearer |
| Derived attributes | /total | No marker | Name it totalDerived or explain |
| Object diagrams | Underlined obj : Class | No object-diagram type | Use a flowchart if you really need one |
Notes are the most useful escape hatch:
classDiagram
class Compartment {
-Size size
-bool free
}
note for Compartment "At most one active Delivery at a time. Enforced by LockerService."
4.9 Generics in Mermaid
Mermaid writes type parameters between tildes. List~Compartment~ renders as List<Compartment>, and nesting works: List~List~int~~. A generic class declares its parameter in the class name: class Repository~T~.
classDiagram
class Repository~T~ {
<<interface>>
+findById(String id) T
+save(T item) void
+findAll() List~T~
}
class DeliveryRepository
Repository~T~ <|.. DeliveryRepository
Two things trip people up. First, Mermaid's documentation states that generics containing a comma, such as Map~K, V~ nested inside another type, aren't reliably supported; if a Map type gets mangled, write the field's type in words (-byId : map of TrackingId to Delivery) or use a note. Second, don't put < and > in member text to show generics, because Mermaid may treat them as markup. Use tildes.
5. Sequence diagrams for flows
A class diagram can be entirely plausible and still not work. A sequence diagram tests one scenario against it: every arrow must be an operation on the receiving class, and every sender must have a way to reach the receiver (a field, a parameter, a return value). If you can't draw the arrow, the class diagram is missing a relationship.
5.1 The notation you need
| Element | Meaning | Mermaid |
|---|---|---|
| Participant | An object (lifeline) | participant S as LockerService |
| Actor | A human or external system | actor C as Courier |
| Synchronous call | Caller waits for the result | A->>B: op(args) |
| Return | Result of a synchronous call; show only when it carries data | B-->>A: result |
| Asynchronous message | Caller doesn't wait (events, queues, hardware signals) | A-)B: event |
| Asynchronous reply | A later callback | B--)A: callback |
| Lost or failed message | Message that may not arrive | A-xB: msg |
| Self-call | An object calls its own method | A->>A: helper() |
| Activation bar | The participant is executing | A->>+B: op then B-->>-A: r, or activate B / deactivate B |
| Creation | Object created during the scenario | create participant D as Delivery then A->>D: new |
| Note | Commentary | Note over A,B: text |
| Numbering | Step numbers on every message | autonumber |
Synchronous versus asynchronous is the distinction that matters most in LLD. A method call is synchronous: the caller is blocked until it returns. A door sensor reporting "closed", a message published to a queue, or an SMS handed to a provider are asynchronous: the sender carries on. Drawing them differently shows you understand where the design has to cope with things happening later, or not at all.
5.2 Combined fragments
Fragments are boxes around part of the diagram that add control flow.
| Fragment | Meaning | Use it for |
|---|---|---|
alt / else | Exactly one branch runs | Success versus failure, a choice of strategy |
opt | Runs only if the condition holds | An optional step, such as a reminder or a receipt |
loop | Repeats | Retries, polling, iterating over items |
par / and | Branches run concurrently | Notifying two parties at once |
break | Leaves the enclosing fragment if the condition holds | Lockout, abort, early exit |
critical / option | A region that must run atomically, with alternatives | Taking a lock, a transaction |
rect | Highlights a region (Mermaid extra, not UML) | Drawing attention |
Mermaid closes every fragment with end. That keyword is why end can't be used as a participant or node name.
5.3 Deposit flow
sequenceDiagram
autonumber
actor C as Courier
participant K as Kiosk
participant S as LockerService
participant A as AllocationStrategy
participant D as Door
participant N as Notifier
C->>+K: scan parcel TRK-1
K->>+S: startDeposit(TRK-1, SMALL)
S->>+A: choose(free compartments, SMALL)
A-->>-S: compartment 07
alt a compartment fits
S->>S: delivery.assign(07)
S-)D: unlock(07)
S-->>K: put parcel in door 07
D--)S: doorClosed(07)
S->>S: delivery.deposit(now), generate code
S-)N: notifyReady(recipient, code)
else nothing fits
S-->>K: station full, use another station
end
deactivate S
K-->>-C: show result
What this diagram tells the interviewer:
- Two asynchronous edges.
unlockdoesn't return "door closed"; the door later sends its own event. The design therefore needs a waiting state (ASSIGNED) and a timeout for the case where the event never comes. That's exactly what the state diagram in section 6 adds. - The strategy is called, not embedded. The arrow to
AllocationStrategyshows the variation point is real. - Notification is fire-and-forget. If the SMS provider is slow, the courier isn't kept waiting. A follow-up question will be "what if the SMS fails?", and an answer is "the notifier retries from an outbox; the delivery is already deposited either way".
Race condition the diagram exposes
Step 3 (choose) and the reservation in step 5 are two separate calls. If two couriers scan at the same moment, both could be offered compartment 07. Either the choice and the reservation must be one atomic operation on the station, or the reservation must be a compare-and-set that fails if the compartment is already taken. A sequence diagram is a good place to circle that gap; the concurrency lessons cover the fixes.
5.4 Pickup flow
sequenceDiagram
actor R as Recipient
participant K as Kiosk
participant S as LockerService
participant DL as Delivery
participant D as Door
R->>K: open pickup screen
loop each attempt
R->>K: enter code
K->>+S: pickUp(station, code)
S->>+DL: verify(code, now)
DL-->>-S: match, mismatch or blocked
break delivery is blocked after 5 wrong codes
S-->>K: blocked for 15 minutes
K-->>R: show lockout message
end
alt code matches
S-)D: unlock(07)
S->>DL: markPickedUp(now)
S-->>K: door 07 open
K-->>R: take your parcel
else wrong code
S-->>K: wrong code, attempts left
K-->>R: try again
end
deactivate S
end
par after pickup
S-)K: refresh free-compartment count
and
S-)S: publish DeliveryPickedUp event
end
Notice where the decisions live. verify is a method on Delivery, not on LockerService, because the attempt counter and the lockout rule are about that delivery. The sequence diagram makes that choice visible: the service asks, the entity decides. If your diagram shows the service reading failedAttempts and comparing it to 5 itself, that's the anaemic-model smell discussed in From Nouns to Classes.
5.5 Rules for interview sequence diagrams
- One scenario per diagram. If you need more than two
altfragments, you're drawing several scenarios at once; split them or pick the most important one. - Names must match the class diagram. If the sequence diagram calls
delivery.verify(code), the class box needsverify. Mismatches are the most common error. - Show returns only when they carry information. A
voidcall needs no dashed return arrow. - Don't draw getters.
S->>DL: getFailedAttempts()belongs in neither the diagram nor the design. - Start with the actor's intention, not the UI's. "scan parcel" is better than "press button 3".
- Mark asynchronous edges honestly. Hardware, queues, webhooks and timers are asynchronous. Each one implies a waiting state and a timeout somewhere.
- Keep it to about 6 participants. More than that is usually a sign the scenario is too big, or the design has too many layers for an interview.
6. State diagrams for lifecycle-heavy entities
Some entities are essentially a status with rules attached: an order, a booking, a ticket, an elevator, a vending machine, a parcel. For these, the most important design question is which operations are legal in which status, and a state diagram answers it better than anything else.
When an entity deserves a state diagram:
- it has three or more statuses that change over time;
- the same request (cancel, pay, pick up) is allowed in some statuses and refused in others;
- transitions are caused by events from outside: hardware, timers, payments, other users;
- there are timeouts ("if not paid within 15 minutes, release the seats").
6.1 Notation
| Element | UML | Mermaid stateDiagram-v2 |
|---|---|---|
| State | Rounded rectangle | Waiting or state "Waiting for pickup" as Waiting |
| Initial pseudo-state | Filled circle | [*] --> First |
| Final state | Circle with a ring | Last --> [*] |
| Transition | Arrow labelled event [guard] / action | A --> B : event [guard] / action |
| Self-transition | Arrow back to the same state | A --> A : event / action |
| Composite state | State containing a sub-machine | state Deposited { ... } |
| Choice | Diamond, branches on guards | state check <<choice>> |
| Fork / join | Bars splitting into or merging parallel regions | state f <<fork>>, state j <<join>> |
| Concurrent regions | Dashed divider inside a composite state | -- inside a composite state |
| Note | Dog-eared box | note right of A : text |
| History | Circled H: re-enter the last active substate | Not supported in Mermaid |
The transition label event [guard] / action is the most useful piece of UML notation for LLD:
- event: what happens (
doorClosed,cancel,72h elapsed); - guard: a condition that must hold for this transition to fire (
[attempts left],[balance enough]); - action: what the system does as the transition fires (
/ release compartment).
All three map straight onto code: the event is a method, the guard is a check at the top of that method, and the action is its body.
6.2 The delivery lifecycle
stateDiagram-v2
[*] --> Created
Created --> Assigned : courier scans / reserve compartment
Created --> Cancelled : shipment cancelled
Assigned --> Deposited : door closed / generate code, notify
Assigned --> Cancelled : 5 min without door closed / release compartment
state Deposited {
[*] --> Waiting
Waiting --> Reminded : 48h elapsed / send reminder
Waiting --> Blocked : 5th wrong code
Reminded --> Blocked : 5th wrong code
Blocked --> Waiting : 15 min elapsed
}
Deposited --> PickedUp : correct code [not blocked] / open door
Deposited --> Expired : 72h elapsed
Expired --> Returned : courier collects / release compartment
PickedUp --> [*]
Returned --> [*]
Cancelled --> [*]
Things this diagram settles that the class diagram couldn't:
- What a delivery does while it has no compartment. It's
Created, and nothing but assignment or cancellation can happen. - Why
Assignedexists at all. Because the door event is asynchronous (from the sequence diagram), there's a window where the compartment is reserved but the parcel isn't in it. The five-minute timeout is how you stop compartments leaking. - Which events need timers. Three transitions are time-based (48 h, 72 h, 15 min, plus the 5-minute deposit timeout). That tells you the design needs a scheduler or a periodic sweep (
expireOverdue()on the service), and that theClockmust be injectable. - A subtle bug.
Blocked --> Waitingreturns toWaitingeven if the recipient had already been reminded. UML would use a history pseudo-state (re-enter whichever substate was last active), which Mermaid can't draw. In code, the fix is areminderSentflag instead of a substate. Spotting this kind of thing is exactly what state diagrams are for.
6.3 Three more lifecycles you'll meet
An online order
stateDiagram-v2
[*] --> BeforeShipping
state BeforeShipping {
[*] --> Placed
Placed --> Paid : payment captured
Placed --> PaymentFailed : payment declined
PaymentFailed --> Paid : retry succeeds
Paid --> Packed : warehouse packs
Packed --> [*]
}
BeforeShipping --> Cancelled : cancel / refund if paid
BeforeShipping --> Shipped : handed to carrier
Shipped --> Delivered : proof of delivery
Shipped --> Lost : carrier reports loss / refund
Delivered --> ReturnRequested : return within 30 days
ReturnRequested --> Refunded : item received and inspected
Delivered --> [*]
Refunded --> [*]
Cancelled --> [*]
Lost --> [*]
The composite state BeforeShipping captures the most common rule in order systems in a single arrow: you can cancel any time before shipping, and not after. Without the composite you'd draw three separate cancel arrows (from Placed, PaymentFailed, Paid and Packed) and the reader would have to spot that they're the same rule. The completion transition from BeforeShipping to Shipped (the inner machine reaches its final state, then "handed to carrier" fires) is UML's way of saying "only once packed".
An elevator car
stateDiagram-v2
[*] --> Idle
Idle --> MovingUp : request above
Idle --> MovingDown : request below
Idle --> DoorsOpen : request at this floor
MovingUp --> Stopping : nearing a requested floor
MovingDown --> Stopping : nearing a requested floor
Stopping --> DoorsOpen : arrived / chime
DoorsOpen --> DoorsOpen : obstruction / restart timer
DoorsOpen --> DoorsClosing : timer expired
DoorsClosing --> DoorsOpen : obstruction or call at this floor
DoorsClosing --> Idle : closed [no pending requests]
DoorsClosing --> MovingUp : closed [requests ahead going up]
DoorsClosing --> MovingDown : closed [requests ahead going down]
Idle --> Maintenance : key switch
Maintenance --> Idle : key switch
Here the interesting part is the guards on the transitions out of DoorsClosing. They're where the scheduling strategy plugs in: "requests ahead going up" is a question the car asks its dispatch strategy. The state machine says when the car decides where to go next, and the strategy says what it decides. That's a clean split between the State and Strategy patterns, and it's a good thing to say aloud in an elevator interview. Also note the safety property the diagram makes checkable: there's no arrow from DoorsOpen straight to either moving state.
A vending machine
stateDiagram-v2
state check <<choice>>
[*] --> Idle
Idle --> HasCredit : coin inserted / add to credit
HasCredit --> HasCredit : coin inserted / add to credit
HasCredit --> Idle : refund pressed / return credit
HasCredit --> check : item selected
check --> HasCredit : [sold out] / show sold out
check --> HasCredit : [credit below price] / show price
check --> Dispensing : [credit covers price]
Dispensing --> Idle : item taken / return change
Idle --> OutOfService : fault detected
HasCredit --> OutOfService : fault detected / return credit
OutOfService --> Idle : engineer reset
The choice pseudo-state turns "select an item" into one event with three guarded outcomes, which is exactly how the code will look: one select(slot) method with two early returns. The vending machine case study draws a different but compatible machine; comparing the two is a good exercise in how much a state diagram depends on the requirements you agreed.
6.4 From a state diagram to code
There are two standard ways to implement a state machine, and the diagram helps you choose.
A transition table works when states mostly differ in which events they accept, not in what they do. Each arrow becomes one row, and anything not in the table is refused. Here's the top level of the delivery lifecycle (the substates of Deposited become fields, as discussed above). All three versions were run, and each asserts that an expired parcel can't be picked up.
import java.util.EnumMap;
import java.util.Map;
public class DeliveryLifecycle {
enum State { CREATED, ASSIGNED, DEPOSITED, PICKED_UP, EXPIRED, RETURNED, CANCELLED }
enum Event { ASSIGN, DEPOSIT, PICK_UP, EXPIRE, COLLECT_FOR_RETURN, CANCEL }
// Every arrow in the state diagram is one row here. Anything missing is an illegal transition.
private static final Map<State, Map<Event, State>> TRANSITIONS = new EnumMap<>(State.class);
private static void allow(State from, Event on, State to) {
TRANSITIONS.computeIfAbsent(from, s -> new EnumMap<>(Event.class)).put(on, to);
}
static {
allow(State.CREATED, Event.ASSIGN, State.ASSIGNED);
allow(State.CREATED, Event.CANCEL, State.CANCELLED);
allow(State.ASSIGNED, Event.DEPOSIT, State.DEPOSITED);
allow(State.ASSIGNED, Event.CANCEL, State.CANCELLED);
allow(State.DEPOSITED, Event.PICK_UP, State.PICKED_UP);
allow(State.DEPOSITED, Event.EXPIRE, State.EXPIRED);
allow(State.EXPIRED, Event.COLLECT_FOR_RETURN, State.RETURNED);
}
static final class Delivery {
private State state = State.CREATED;
State state() { return state; }
void fire(Event event) {
State next = TRANSITIONS.getOrDefault(state, Map.of()).get(event);
if (next == null) throw new IllegalStateException(event + " is not allowed in " + state);
state = next;
}
}
public static void main(String[] args) {
Delivery d = new Delivery();
d.fire(Event.ASSIGN);
d.fire(Event.DEPOSIT);
d.fire(Event.EXPIRE);
try { d.fire(Event.PICK_UP); throw new AssertionError("picked up an expired parcel"); }
catch (IllegalStateException expected) { }
d.fire(Event.COLLECT_FOR_RETURN);
if (d.state() != State.RETURNED) throw new AssertionError();
System.out.println("lifecycle checks passed");
}
}
from enum import Enum, auto
class State(Enum):
CREATED = auto()
ASSIGNED = auto()
DEPOSITED = auto()
PICKED_UP = auto()
EXPIRED = auto()
RETURNED = auto()
CANCELLED = auto()
class Event(Enum):
ASSIGN = auto()
DEPOSIT = auto()
PICK_UP = auto()
EXPIRE = auto()
COLLECT_FOR_RETURN = auto()
CANCEL = auto()
# Every arrow in the state diagram is one entry. Anything missing is an illegal transition.
TRANSITIONS: dict[tuple[State, Event], State] = {
(State.CREATED, Event.ASSIGN): State.ASSIGNED,
(State.CREATED, Event.CANCEL): State.CANCELLED,
(State.ASSIGNED, Event.DEPOSIT): State.DEPOSITED,
(State.ASSIGNED, Event.CANCEL): State.CANCELLED,
(State.DEPOSITED, Event.PICK_UP): State.PICKED_UP,
(State.DEPOSITED, Event.EXPIRE): State.EXPIRED,
(State.EXPIRED, Event.COLLECT_FOR_RETURN): State.RETURNED,
}
class Delivery:
def __init__(self) -> None:
self.state = State.CREATED
def fire(self, event: Event) -> None:
nxt = TRANSITIONS.get((self.state, event))
if nxt is None:
raise RuntimeError(f"{event.name} is not allowed in {self.state.name}")
self.state = nxt
d = Delivery()
for e in (Event.ASSIGN, Event.DEPOSIT, Event.EXPIRE):
d.fire(e)
try:
d.fire(Event.PICK_UP)
raise AssertionError("picked up an expired parcel")
except RuntimeError:
pass
d.fire(Event.COLLECT_FOR_RETURN)
assert d.state is State.RETURNED
print("lifecycle checks passed")
type State = "CREATED" | "ASSIGNED" | "DEPOSITED" | "PICKED_UP" | "EXPIRED" | "RETURNED" | "CANCELLED";
type DeliveryEvent = "ASSIGN" | "DEPOSIT" | "PICK_UP" | "EXPIRE" | "COLLECT_FOR_RETURN" | "CANCEL";
// Every arrow in the state diagram is one entry. Anything missing is an illegal transition.
const TRANSITIONS: Record<State, Partial<Record<DeliveryEvent, State>>> = {
CREATED: { ASSIGN: "ASSIGNED", CANCEL: "CANCELLED" },
ASSIGNED: { DEPOSIT: "DEPOSITED", CANCEL: "CANCELLED" },
DEPOSITED: { PICK_UP: "PICKED_UP", EXPIRE: "EXPIRED" },
EXPIRED: { COLLECT_FOR_RETURN: "RETURNED" },
PICKED_UP: {},
RETURNED: {},
CANCELLED: {},
};
class Delivery {
private current: State = "CREATED";
get state(): State {
return this.current;
}
fire(event: DeliveryEvent): void {
const next = TRANSITIONS[this.current][event];
if (!next) throw new Error(`${event} is not allowed in ${this.current}`);
this.current = next;
}
}
const d = new Delivery();
(["ASSIGN", "DEPOSIT", "EXPIRE"] as const).forEach((e) => d.fire(e));
let refused = false;
try {
d.fire("PICK_UP");
} catch {
refused = true;
}
if (!refused) throw new Error("picked up an expired parcel");
d.fire("COLLECT_FOR_RETURN");
if (d.state !== "RETURNED") throw new Error(d.state);
console.log("lifecycle checks passed");
The table is the diagram written as data. Reviewing one against the other takes a minute, and a test can walk every row.
The State pattern (one class per state, each implementing the events it accepts) is better when states behave differently, not just accept different events. A vending machine in HasCredit does real work on select that Idle doesn't do at all. The cost is one class per state, so for an entity with seven states and almost no per-state behaviour, a table or an enum with a switch is the simpler, more honest choice. The behavioural patterns overview describes the State pattern; the vending machine and ATM case studies use it.
7. Activity diagrams and flowcharts
An activity diagram shows a process: steps, decisions, loops, parallel branches, and optionally which participant does each step (swimlanes). Where a state diagram is about one object's lifecycle, an activity diagram is about a procedure that may involve several.
UML activity notation, briefly:
- action: a rounded box, one step;
- decision and merge: diamonds where the flow splits on a condition and joins again;
- fork and join: thick bars where the flow splits into parallel branches and waits for all of them;
- partitions (swimlanes): columns or rows showing who does each action;
- initial and final nodes: a filled circle and a ringed circle, as in state diagrams;
- object flow: an object box on an edge, showing data passed between actions.
Mermaid has no activity-diagram type. Use a flowchart, with stadium shapes for start and end, diamonds for decisions and subgraphs for swimlanes. That's what nearly everyone does, and interviewers accept it.
7.1 The pickup process
flowchart TB
subgraph Recipient["Recipient"]
start(["Arrives at kiosk"]) --> enter["Type pickup code"]
take["Take parcel, close door"] --> doneNode(["Done"])
leave(["Leaves, tries later"])
end
subgraph Kiosk["Kiosk"]
show["Show result"]
end
subgraph Service["LockerService and Delivery"]
find{"Delivery found<br/>at this station?"}
blocked{"Blocked?"}
expired{"Expired?"}
match{"Code matches?"}
count["Increment failed attempts"]
five{"5th failure?"}
block["Block for 15 minutes"]
open["Unlock door, mark picked up"]
notify["Notify sender, free compartment"]
end
enter --> find
find -->|"no"| show
find -->|"yes"| blocked
blocked -->|"yes"| show
blocked -->|"no"| expired
expired -->|"yes"| show
expired -->|"no"| match
match -->|"no"| count --> five
five -->|"no"| show
five -->|"yes"| block --> show
match -->|"yes"| open --> notify
open --> take
show --> retry{"Try again?"}
retry -->|"yes"| enter
retry -->|"no"| leave
The order of the checks is a design decision, and the diagram makes it reviewable. Checking "blocked" before "matches" means a blocked delivery can't be opened even with the right code, which is the point of a lockout. Checking "expired" before "matches" means an expired parcel stays shut even if the code is right, because a courier may already be on the way to collect it. An interviewer can disagree with either order, and now there's something concrete to disagree with.
Notice also that "found at this station" matters for security. A code is only valid at the station holding the parcel, so a guessed code can't open a compartment elsewhere. That's the non-functional requirement "a code must never open the wrong compartment" turned into a step.
7.2 When to draw one, and when not
| Situation | Better diagram | Why |
|---|---|---|
| A procedure with several ordered checks and early exits | Activity | Shows order and every exit at once |
| A business process across several people or teams | Activity with swimlanes | Shows hand-offs |
| An algorithm with a loop and a decision (dispatch, allocation) | Activity | Easier to follow than pseudo-code for some readers |
| Which object calls which, in what order | Sequence | Activity diagrams hide the objects |
| What one entity allows in each status | State | Activity diagrams hide the statuses |
In an interview, an activity diagram is usually a response to "walk me through how X works". Two minutes of flowchart can replace five minutes of hand-waving. If nobody asks, you rarely need one.
8. One example, four views: how they check each other
The value of drawing more than one diagram is that they cross-check. For the locker:
| Check | Between | What it caught here |
|---|---|---|
| Every message in a sequence diagram is an operation on the receiving class | Sequence → Class | confirmDeposit had to be added to LockerService to handle the door event |
| Every sender can reach its receiver | Sequence → Class | LockerService --> Notifier must be an association, not a dependency, because the service sends notifications without being handed a notifier each time |
| Every state in the state diagram is a value of the status enum | State → Class | DeliveryState gained ASSIGNED and CANCELLED once the asynchronous door event was understood |
| Every asynchronous edge has a waiting state and a timeout | Sequence → State | The 5-minute Assigned → Cancelled timeout |
| Every guard is a check in a method | State → Code | [not blocked] became the first check in Delivery.verify |
Every decision in the activity diagram appears as an alt, opt or break in a sequence diagram, or as a guard | Activity → Sequence, State | The "blocked" check became a break fragment in the pickup sequence |
| Every timed transition has something that fires it | State → Class | expireOverdue() on the service, driven by the injected Clock |
You don't need all four diagrams in every interview; usually the class diagram plus one of the others is right. But knowing these checks lets you use whichever second diagram you draw to test the first.
9. Common notation mistakes
- Composition where there is no ownership.
Library *-- Memberclaims that deleting the library deletes the people. Use association. The test: does the part's lifetime really end with the whole's, and can it belong to only one? - Diamond at the wrong end. The diamond goes on the whole.
Compartment *-- LockerStationsays compartments own stations. - Inheritance arrow pointing at the child. The triangle points at the parent. In Mermaid,
Parent <|-- Child. - Solid line for implements. Realization is dashed (
<|..). A solid triangle meansextends. - Dependency drawn as association. If the class has no field of that type, it's a dependency (dashed). Too many solid lines suggests coupling that isn't there.
- Multiplicity on the wrong end.
Customer "*" --> "1" Ordersays each customer has one order and each order has many customers. Put the number next to the class it counts. - Missing multiplicity on core relationships. Leaving it off avoids the decision but doesn't remove it. Write it on the three or four relationships that matter.
- Every getter and setter listed. It hides the behaviour that matters and suggests a data-bag design.
- Public fields everywhere.
+balanceinvites any caller to break invariants. Mark state-and show the operations that change it. - A class for every noun. Dates, names and amounts usually belong as attributes or small value objects, not top-level boxes. From Nouns to Classes covers this in detail.
- Sequence diagram that disagrees with the class diagram. Calling methods that aren't in any class box, or calling objects nobody holds a reference to.
- Returns drawn for every call. Clutters the diagram. Draw returns that carry data the caller uses.
- Synchronous arrow for an event. A door sensor, a payment webhook or a timer is asynchronous. Drawing it synchronous hides the waiting state you need.
- State diagram with statuses but no events. Arrows without labels say nothing. Every transition needs at least an event; add guards and actions where they matter.
- States that are really activities. "Validating payment" is usually a step inside a transition, not a state, unless it can take long enough that other events can arrive while it's in progress.
- Using
endas a name. Mermaid closes blocks withend, so a node or participant calledendbreaks the diagram. UsedoneNodeor similar. - Semicolons in sequence messages. Mermaid treats
;as a line break inside a sequence diagram. Use a comma or a dash. - Unquoted special characters in flowchart labels. A label containing
(,[,:,/or similar must be in double quotes:A["Retry (backoff)"].
10. Quick reference
| Want to show | Diagram | Mermaid |
|---|---|---|
| Class with members | Class | class A { -int x +op(T p) R } |
| Static, abstract member | Class | +make()$ A, #hook()* void |
| Interface, abstract class, enum | Class | <<interface>>, <<abstract>>, <<enumeration>> |
| Generic type | Class | List~Item~, class Repo~T~ |
| Dependency | Class | A ..> B |
| Association (navigable to B) | Class | A --> B |
| Aggregation | Class | Whole o-- Part |
| Composition | Class | Whole *-- Part |
| Inheritance | Class | Parent <|-- Child |
| Implements | Class | Iface <|.. Impl |
| Multiplicity and label | Class | A "1" --> "0..*" B : label |
| Note | Class | note for A "text" |
| Layout direction | Class, flowchart | direction LR |
| Sync call, return | Sequence | A->>B: op(), B-->>A: r |
| Async message, async reply | Sequence | A-)B: evt, B--)A: cb |
| Activation | Sequence | A->>+B: op, B-->>-A: r |
| Branches, optional, loop | Sequence | alt ... else ... end, opt ... end, loop ... end |
| Parallel, early exit, atomic | Sequence | par ... and ... end, break ... end, critical ... end |
| Step numbers | Sequence | autonumber |
| Start, end | State | [*] --> A, A --> [*] |
| Transition with guard and action | State | A --> B : event [guard] / action |
| Composite state | State | state A { [*] --> A1 } |
| Choice | State | state c <<choice>> |
| Fork, join | State | state f <<fork>>, state j <<join>> |
| Decision | Activity (flowchart) | D{"Question?"} |
| Swimlane | Activity (flowchart) | subgraph Lane["Who"] ... end |
| Start, end node | Activity (flowchart) | s(["Start"]), doneNode(["Done"]) |
11. Interview questions
Q1. What's the difference between aggregation and composition, and does it matter in practice?
Answer
Both are whole-part relationships. In composition the part belongs to one whole at a time and its lifetime ends with the whole's; in aggregation the part exists independently and may be shared. It matters because composition marks an ownership boundary: the whole is responsible for creating its parts, keeping them consistent and deleting them, and outside code shouldn't hold references to the parts. That boundary is usually also the transactional and locking boundary (an aggregate, in DDD terms). Aggregation's meaning is deliberately loose in UML 2, so many teams just use association for it, but composition is worth getting right.
Q2. You've drawn Order --> Customer. The interviewer asks "why not both directions?" What do you say?
Answer
Bidirectional associations cost more: both ends must be kept consistent, which means one side has to update the other, and they create cycles that complicate serialisation and garbage collection in some runtimes. I'd make it one-way unless a use case needs navigation in the other direction. "Show a customer's orders" can be a repository query (orders.findByCustomer(id)) instead of a List<Order> on Customer, which also stops Customer from growing without bound.
Q3. When would you draw a state diagram in an LLD interview?
Answer
When one entity has three or more statuses, and which operations are legal depends on the status, especially if transitions come from timers or external events. Orders, bookings, tickets, elevators, vending machines and parcels are typical. It takes two or three minutes and usually exposes missing states (a waiting state for an asynchronous event, a timeout), which saves time when coding.
Q4. How do you show an asynchronous call in a sequence diagram, and why does it matter for the design?
Answer
With an open arrowhead (-) in Mermaid) instead of a filled one, and no return arrow, because the caller doesn't wait. It matters because anything asynchronous may arrive late or not at all. The design needs a state in which the object waits for the event, a timeout for when it never arrives, and usually idempotency in case it arrives twice.
Q5. Your class diagram has Student and Course with many-to-many. Where does the grade go?
Answer
On neither. The grade belongs to the relationship, so it needs an association class, which in practice (and in Mermaid, which has no association-class notation) is a real class such as Enrolment with a link to one student and one course, holding the grade and enrolment date. Each side has a one-to-many relationship with Enrolment.
Q6. What's wrong with this: class Account { +double balance }?
Answer
Three things. The balance is public, so any caller can set it and skip the rules for deposits and withdrawals. It's a double, which can't represent most decimal amounts exactly, so money should be a value object holding integer minor units or a decimal type. And there are no operations shown, so the reader can't tell what an account does. Better: -Money balance, +deposit(Money m) void, +withdraw(Money m) void.
Q7. Transition table or State pattern for a state machine?
Answer
Use a table, or an enum with a switch, when states differ mainly in which events they accept and the actions are small. It's compact, easy to review against the diagram, and easy to test by walking each row. Use the State pattern when each state has substantial behaviour of its own, so that a single class with a switch in every method would become hard to read. The cost of the pattern is one class per state, plus the problem of where shared data lives.
Q8. What does event [guard] / action mean on a transition, and how does it map to code?
Answer
The event triggers the transition; the guard is a condition that must be true for it to fire; the action runs as it fires. In code, the event is a method (pickUp(code)), the guard is a check near the top that returns early or throws (if blocked: refuse), and the action is the body that changes state and performs side effects (unlock door, state = PICKED_UP).
Q9. When is an activity diagram better than a sequence diagram?
Answer
When the interesting part is the order of steps and decisions rather than which object performs them, such as a chain of validation checks with early exits, a retry and escalation process, or a business process with hand-offs between people. A sequence diagram puts objects first and gets cluttered with many branches; an activity diagram puts control flow first.
Q10. Name three things Mermaid's class diagrams can't express that UML can, and how you'd work around them.
Answer
Association classes (promote to a real class with two associations), qualified associations (show a map-typed field or explain it), and constraints like {ordered} (use a note for). Others: role names at both ends (put the role in the single label), n-ary associations (promote to a class), and the "not navigable" x mark (show navigability only with arrowheads).
Q11. The interviewer says your diagram has too many classes. How do you decide what to cut?
Answer
I'd look for boxes with no behaviour, which are usually attributes or value objects that can be folded into their owner (an Address that only holds strings could become a field until it gains rules). Then I'd look for classes that only forward calls, and for an inheritance hierarchy where subclasses differ only in data, which can become one class with a field or an enum. What I'd keep: anything that enforces a rule, anything that's a variation point the requirements asked for, and the entities with identity.
Q12. How do you keep the diagram and the code consistent during the interview?
Answer
Draw the class diagram before coding, keep it visible, and whenever the code adds a field, changes a relationship or moves a method, update the diagram straight away. It takes seconds. At the end, walk the main flow pointing at both. If they disagree, the interviewer will assume the code is right and the diagram was decoration.
Related pages
- Object-Oriented Programming: the concepts the diagrams describe
- OOP Concepts in Depth & UML Class Diagrams: the basic notation, plus library and parking-lot models
- From Nouns to Classes: Domain Modelling for LLD: deciding what goes in the boxes
- The LLD Interview Framework: where each diagram fits in the 45 minutes
- Common LLD Mistakes
- Behavioural Design Patterns: State, Strategy, Observer
- Design a Vending Machine and Design an Elevator System: state machines in full case studies
- Low-Level Design Course