Notes
The problem
Here is why order matters. Our classes are fine: a booking service, a seat inventory and a payment gateway. But the first version charges the card, and only then tries to hold the seat. Two passengers click on seat fourteen at the same moment, both are charged, and only one gets the seat. The other needs a refund and is angry. The class diagram looked perfect. The bug was in the sequence.
The idea
A sequence diagram shows one scenario over time. The objects that take part are lined up across the top, usually from the user on the left toward storage and outside systems on the right. Time flows down the page. Each arrow is a message, normally a method call, from one object to another. Read it from top to bottom like a story. One diagram describes one scenario, like booking two seats where payment works.
- objects across the top,
- left to right
- time flows top to bottom
- arrows are messages
- (method calls) between them
- one diagram = one scenario
- e.g. "book two seats,
- payment succeeds"
Lifelines
Each participant gets a lifeline: a box with its name at the top and a dashed line dropping down the page. The user is often drawn as a stick figure, called an actor. When an object is busy running a method, a thin rectangle called an activation bar sits on its lifeline. The bar starts when a call arrives and ends when the method returns, so you can see at a glance who is waiting for whom.
Passenger BookingService SeatInventory | | | |---book()---># | | #---hold()-----># | #<--- ok -------# | # | # activation bar: the object is busy running a method
Kinds of message
There are a few kinds of arrow. A synchronous call is a solid line with a filled arrowhead: the caller waits for the answer, like a normal Java method call. An asynchronous message is a solid line with an open arrowhead: the caller sends it and carries on, like putting a job on a queue. A return is a dashed line going back. A call to your own method loops back to your own lifeline, and creating a new object points at its box.
- synchronous call:
- solid line, filled head
- the caller waits
- asynchronous message:
- solid line, open head
- the caller moves on
- return: dashed line back
- self call: arrow loops back
- to the same lifeline
- create: dashed, to a new box
The happy path
Here is the fixed flow, the happy path. The passenger asks the booking service to book seats fourteen and fifteen on bus seven. The service first asks the seat inventory to hold both seats. Only then does it charge eighteen hundred rupees. When the charge succeeds, it confirms the seats, saves the booking, and sends the e-ticket as an asynchronous message, without waiting. The diagram makes the safe order impossible to miss.
The loop frame
Repeated steps go inside a frame, a rectangle with a small label in the corner. A loop frame repeats its messages, and the condition is written in square brackets, called a guard, like for each seat. Inside, the service tries to hold one seat at a time, and the inventory answers true or false. In Java, that is just a for loop. If any seat fails, the service releases the ones it already held.
BookingService SeatInventory
| +-loop [for each seat]------+
| | |---tryHold(seat)--->| |
| | |<-- true / false ---| |
| +--------------------------+
Java: for (int s : seats)
held &= tryHold(s); The alt frame
Failures go in an alt frame, short for alternatives. It is split by a dashed line into branches, and each branch has a guard. In the payment ok branch, we confirm, save and notify. In the declined branch, we release both seats so other passengers can buy them, and return a failure. In Java an alt frame is an if and else. Drawing it forces you to decide what happens on failure, which is what interviewers want to hear.
- +-alt [payment ok]--------+
- | confirm seats |
- | save booking |
- | send e-ticket |
- |- - [declined] - - - - - -|
- | release seats |
- | return failure |
- +-------------------------+
Other frames
A few more frame labels are worth knowing. Opt is an optional block, an if with no else, such as apply a coupon only if the passenger has one. Par shows branches that run in parallel. Break stops the rest of the flow, for example when a seat is not available. And ref points to another diagram, so you can keep each one small instead of drawing the whole system on one page.
- opt [has coupon]
- steps that may be skipped
- par
- branches that run at the
- same time
- break
- stop the flow here
- ref
- points to another diagram
- (keeps each one small)
Sync vs async
Notice the two different arrowheads at the end. Saving the booking is synchronous. The service waits for the store to confirm, because without a saved record we cannot promise the passenger anything. Sending the e-ticket is asynchronous. The service hands it off and replies to the passenger at once. If the message is slow, the booking is still done. The diagram makes this design choice visible with one small arrowhead.
Diagram to code
Here is the booking method, and you can lay it beside the diagram. Hold all seats, or fail with taken. Charge the card. If it is declined, release the seats and fail. That is the alt frame. Otherwise confirm the seats, save the booking, and queue the e-ticket. Each arrow leaving the booking service lifeline is one line in this method, in the same order. A good sequence diagram is almost pseudo code.
if (!seats.holdAll(wanted))
return Result.failed("taken");
if (!pay.charge(card, price)) {
seats.releaseAll(wanted);
return Result.failed("declined");
}
seats.confirmAll(wanted);
Booking b = store.save(...);
notifier.sendLater(b);
return Result.success(b); Drawing it fast
In an interview, draw one flow, usually the most important use case. Put the actor on the left, then the main service, then its helpers. Draw only the calls that matter, and skip getters and obvious returns. Add one alt frame for the main failure, like payment declined, and mark asynchronous messages clearly. Talk while you draw. Five lifelines and ten arrows explain more than a page of text.
- 1 choose ONE flow: the most
- important use case
- 2 lifelines: actor, service,
- then helpers left to right
- 3 arrows for real calls only
- 4 one alt for the main
- failure
- 5 mark async with "async"
- skip getters and returns
- that add nothing
Which diagram when
Which diagram should you draw? A class diagram shows structure: what exists and how it is connected. It does not change over time. A sequence diagram shows behaviour: one scenario in time order. Activity diagrams show the steps of a process, and state diagrams show the states of one object, like a booking going from held to paid to cancelled. In most design rounds, one class diagram plus one sequence diagram is the right amount.
- class diagram:
- what exists and how it
- is connected (static)
- sequence diagram:
- one scenario, in time
- order (dynamic)
- activity / state diagram:
- steps of a process, or
- states of one object