From Nouns to Classes: Domain Modelling for LLD
Every LLD interview starts the same way: a few sentences describing a system, and a blank board. The first real design decision is which classes exist, and it's the one that decides most of what follows. If you choose the wrong classes, every later step is harder: rules end up in the wrong place, a "manager" class grows to 600 lines, and the interviewer's first extension question forces a rewrite. With the right classes, patterns tend to fall into place on their own and the code stays short.
This page is about making that first decision deliberately. It starts with the classic technique of extracting nouns and verbs, and spends as much time on where that technique misleads you as on how to use it. Then it covers the modelling ideas that do most of the work in practice: assigning responsibilities, telling entities from value objects, drawing aggregate boundaries around invariants, choosing between an enum and a class hierarchy, and getting money, time and IDs right. It finishes with a complete worked example that goes from a problem statement to running code in three languages.
Key Takeaway
Nouns give you candidates, not classes. A class earns its place by owning a rule or a responsibility. Things with an identity that persists while their attributes change are entities; things defined entirely by their values are value objects. Group objects that must stay consistent together into an aggregate with one root that enforces the rules. Use classes instead of an enum when the kinds behave differently, and never store money in a float.
What this page builds on. Object-Oriented Programming introduces CRC cards and the anaemic-model anti-pattern; OOP Concepts in Depth & UML Class Diagrams has the "nouns become classes, verbs become methods" checklist and the notation; UML for Interviews covers how to draw the result. The DDD pages, especially Tactical Design, go much deeper on entities, value objects and aggregates than an interview needs. This page is the lightweight, interview-sized version, focused on the decisions.
1. What a domain model is for
A domain model is the set of classes that represent the things and rules of the problem: bookings, sessions, members, plans, money. It's distinct from the parts that deal with delivery mechanisms, such as controllers, databases, message queues and UI.
In an LLD interview, the domain model is the design. The interviewer wants to see:
- the right concepts, named the way the problem names them;
- rules in the objects they're about, not scattered through services;
- clear ownership: who creates what, who can change what, what's deleted with what;
- variation points where the problem says something will change;
- types that prevent bugs: a
Moneythat can't be added to a different currency, an ID type that can't be mixed up with another.
A good test of a domain model: read a business rule from the problem statement, and point to the single method that enforces it. If you need to point at three places, or at a service that reaches into five objects' fields, the model needs work.
2. The problem we'll model
We'll use one problem throughout. It's written for this page and deliberately includes the kinds of messiness real problem statements have.
A fitness studio's booking system. The studio runs scheduled classes: spin, yoga, HIIT and others. Each class session has a class type, an instructor, a room, a start time, a length and a capacity. Each class type has a price. Members book a spot in a session. If a session is full, a member can join its waitlist, which is free. When someone with a spot cancels, the first person on the waitlist gets the spot automatically and is notified. Members pay in one of three ways. Drop-in members pay the class price for each booking. Class pack holders bought a number of credits; each booking uses one, and packs expire 90 days after purchase. Unlimited members pay monthly and can book any class while their membership is active. A member can cancel free of charge until 12 hours before the class starts. After that, a drop-in member gets no refund, a class pack holder loses the credit, and an unlimited member pays a 5.00 late-cancellation fee. A waitlisted member is charged only when they get a spot; if their plan can't pay at that point, they're skipped. Front-desk staff check members in when they arrive, from 30 minutes before the start. The studio wants to see revenue per class type each month. A member can hold only one booking per session.
3. Noun and verb extraction
The oldest technique in object-oriented analysis is to underline the nouns (candidate classes and attributes) and the verbs (candidate operations). It's useful because it's mechanical: it gets you from a blank board to a list in two minutes. It's dangerous because it's mechanical: the list is full of things that aren't classes, and it misses some that are.
3.1 Step one: list every noun phrase
From the statement above: studio, booking system, class, spin, yoga, HIIT, class session, class type, instructor, room, start time, length, capacity, price, member, spot, session, waitlist, someone, spot, first person, way (to pay), drop-in member, class price, booking, class pack holder, number of credits, credit, pack, purchase, unlimited member, membership, charge, late-cancellation fee, refund, front-desk staff, revenue, month.
3.2 Step two: classify each one
Every candidate gets one of these labels. The labels matter more than the list.
| Noun | Decision | Reason |
|---|---|---|
| studio | out of scope (or the service's name) | There's one studio; it's the system boundary, not an object inside it |
| booking system | out of scope | The system itself is never a class in its own model |
| class, class session, session | entity: Session | Synonyms. "Class" is ambiguous (type or occurrence), so pick one precise name |
| class type, spin, yoga, HIIT | value: ClassType | Spin and yoga are instances of class type, not subclasses. They differ in data (name, price), not behaviour |
| instructor | attribute for now (instructorId) | No rules about instructors in the statement. Promote to an entity when a rule appears ("an instructor can't teach two sessions at once") |
| room | attribute for now | Same reasoning as instructor |
| start time, length | value: TimeSlot | Always used together; one rule each ("has it started", "when does it end") |
| capacity | attribute of Session | A number with one rule, enforced by the session |
| price, class price, fee, charge, refund, revenue | value: Money | All amounts of money. Refunds and fees are money with a sign, not separate classes |
| member, drop-in member, class pack holder, unlimited member, someone, first person | entity: Member | "Drop-in member" is a member with a drop-in plan, not a subtype of member (see 3.3) |
| way to pay, drop-in, class pack, unlimited, membership | polymorphic: Plan with three implementations | Each pays, refunds and expires differently. That's behaviour, so classes |
| credit, number of credits | attribute of ClassPack | A counter with rules owned by the pack |
| purchase | attribute (expiresAt on the pack) | Only its date matters, to compute expiry |
| spot, booking | entity: Booking | "Spot" and "booking" mean the same thing. A booking has an identity and a lifecycle (confirmed, cancelled, checked in) |
| waitlist | part of Session | An ordered queue of waitlisted bookings. It has rules, but they're all about that session's seats |
| front-desk staff | actor | Someone who calls checkIn. No class unless permissions are in scope |
| revenue per class type each month | query | A report computed from bookings, not a stored object |
| month | parameter | A time range for the report |
From about forty noun phrases we get five entities or aggregates (Session, Booking, Member, plus the plan classes), three value objects (Money, TimeSlot, ClassType), an enum we haven't seen yet (booking status, which the statement describes with verbs and adjectives), and a lot of attributes. That ratio is normal. Most nouns are attributes.
3.3 The traps
Synonyms. "Class", "class session" and "session" are one thing; "spot" and "booking" are another. Problem statements use several words for a concept because people do. If you make a class for each word, you get two classes with the same responsibility and an argument about which one to call. Pick one name, say it out loud, and use it everywhere. DDD calls the agreed vocabulary the ubiquitous language; see Strategic Design.
Homonyms. The reverse problem: one word for two concepts. "Class" here means both the type ("spin is a popular class") and the occurrence ("the 6 pm class is full"). Splitting it into ClassType and Session is one of the most valuable decisions in this model, and noun extraction alone won't make it; you have to notice that the word is used two ways.
Types that are really instances. Spin, yoga and HIIT look like subclasses of Class. They aren't: they have the same rules and differ only in name and price. A SpinClass extends ClassType hierarchy means a code change every time the studio adds Pilates. If the difference is data, use data.
Roles that look like types. "Drop-in member", "class pack holder" and "unlimited member" look like subclasses of Member. They're members with different plans, and a member can switch plans without becoming a different person, so subclassing would mean replacing the member object (and its ID) when they upgrade. Model the role as something the entity has (Member has a Plan), not something it is. This is composition over inheritance applied to modelling.
Attributes that look like classes. "Start time", "capacity", "credit" and "price" are nouns, but each is a value of something else. The question to ask: does it have an identity, or rules of its own? capacity has one rule ("no more confirmed bookings than this"), and that rule is about the session, so it lives in Session.
Implementation nouns. Words like "database", "list", "screen", "API" and "record" sometimes appear in problem statements ("the system stores bookings in a database"). They're about how, not what. Leave them out of the domain model; mention them when discussing persistence.
Reports and queries. "Revenue per class type each month" is a noun phrase, but it's a question you ask of the data, not a thing with a lifecycle. Model it as a method or a query (revenueFor(classType, month)), not a RevenueReport entity. The model must make the question answerable, which here means each booking records how much was charged.
Missing nouns. Some important concepts aren't nouns in the statement at all. Booking status appears only as verbs and adjectives: "book", "cancel", "waitlisted", "checked in", "late". The concept of a late cancellation, which changes what the plan does, is described as a time rule. Read the verbs and the rules, not only the nouns.
Actors that are also entities. A member is a person who uses the system (actor) and a record the system keeps (entity). Front-desk staff are only actors. An actor becomes an entity only if the system needs to remember something about it.
3.4 Step three: verbs become operations, and each needs an owner
| Verb phrase | Operation | Owner | Why that owner |
|---|---|---|---|
| book a spot | book(member, now) | Session | Capacity, duplicates and the waitlist are all about the session's seats |
| join the waitlist | (part of book) | Session | Joining happens automatically when full |
| cancel | cancel(booking, now) | Session | It frees a seat, which affects the waitlist |
| give the spot to the first person | fillFromWaitlist (private) | Session | A consequence of cancelling, inside the same rule |
| notify | notify(member) | an application service | A side effect outside the domain, triggered by promotion |
| pay, use a credit, charge a fee, refund | chargeBooking, settleCancellation | Plan (via Member) | Each plan's rules differ |
| expire | (checked inside the plan) | ClassPack, Unlimited | Expiry is a property of the plan |
| check in | checkIn(booking, now) | Session | The window depends on the session's time slot |
| see revenue | revenue() | Session (summed by a query) | The session knows its bookings and charges |
Notice the owner column is mostly Session. That isn't a god class in the making; it's a sign that most rules in this problem are about one session's seats. We'll come back to why that makes Session an aggregate root.
4. Finding responsibilities
Extraction gives you a list. Deciding what each class does is a separate step, and the most useful tool for it is still a stack of index cards.
4.1 CRC cards
A CRC card (Class, Responsibilities, Collaborators) is one card per candidate class: the name at the top, what it knows and does on the left, and which other classes it needs on the right. Ward Cunningham and Kent Beck introduced them in 1989 as a teaching tool, and the constraint of a small card is the point: if the responsibilities don't fit, the class is doing too much.
| Session | |
|---|---|
| Knows: its class type, time slot, capacity, bookings, waitlist order | Collaborators: Booking, TimeSlot, Billing (to charge) |
| Does: accept a booking or waitlist it; cancel a booking and promote from the waitlist; check a member in; report its revenue |
| Member | |
|---|---|
| Knows: its ID, name, current plan | Collaborators: Plan |
| Does: pay for a booking through its plan; settle a cancellation through its plan; change plan |
| Plan (DropIn, ClassPack, Unlimited) | |
|---|---|
| Knows: its own terms (credits, expiry, validity, late fee) | Collaborators: Money |
| Does: decide what a booking costs now, or refuse it; decide what a cancellation costs or refunds |
| Booking | |
|---|---|
| Knows: its ID, the member's ID, its status, how much was charged | Collaborators: none |
| Does: record a status change and a charge (as instructed by its session) |
In an interview you won't draw actual cards, but you can talk through the same three columns for each class in a minute. It's a fast way to spot a class with no responsibilities (fold it into another) or one with ten (split it).
4.2 Who knows, who does
The most reliable rule for assigning a responsibility is to give it to the class that has the information needed to carry it out. Craig Larman called this the Information Expert principle. "Can this member book this session?" needs the session's capacity, its bookings and its start time, plus the member's plan. Most of that information is in Session, so Session decides, and asks the plan only the part the plan knows.
The anti-pattern is a service that asks every object for its data and makes the decision itself:
// asks, then decides elsewhere: the rule lives far from the data
if (session.getBookings().size() < session.getCapacity()
&& session.getStart().isAfter(now)
&& member.getPlan().getCredits() > 0) { ... }
The fix is tell, don't ask: send the request to the object that owns the data and let it decide.
// tells: the rule lives with the data it needs
session.book(memberId, now, billing)
A practical test for every responsibility: if this rule changes, which classes do I edit? If the late-cancellation window changes from 12 hours to 24, you should edit one constant in Session. If the class-pack expiry changes, you edit ClassPack. If the answer is "the service, the controller and two entities", the responsibility is in the wrong place. This is also the heart of the Single Responsibility Principle: a class should have one reason to change.
5. Entities and value objects
This distinction is the single most useful modelling idea for LLD after "find the responsibilities".
- An entity has an identity that persists while its attributes change. A member who changes her email and her plan is still the same member. Two members with the same name are still two members. Entities are compared by ID.
- A value object is defined entirely by its attributes. Two
Money(12.50, EUR)values are interchangeable; nobody cares which twelve-fifty it is. Value objects are compared by value, and they should be immutable: to "change" one, you replace it with a new one.
5.1 Identity and equality in code
The two get different equals and hash implementations, and getting this wrong causes real bugs: an entity that uses value equality "disappears" from a hash set when an attribute changes, and two different customers with the same details get merged.
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
// Value object: equal when all its fields are equal. A record gives equals/hashCode for free.
record Email(String value) {
Email {
Objects.requireNonNull(value);
if (!value.contains("@")) throw new IllegalArgumentException("not an email: " + value);
value = value.trim().toLowerCase();
}
}
// Entity: equal when the identity is equal, whatever its other fields say.
final class Customer {
private final String id;
private Email email;
Customer(String id, Email email) { this.id = id; this.email = email; }
void changeEmail(Email newEmail) { this.email = newEmail; }
@Override public boolean equals(Object o) { return o instanceof Customer c && c.id.equals(id); }
@Override public int hashCode() { return id.hashCode(); }
}
public class Equality {
public static void main(String[] args) {
// Two values with the same content are interchangeable.
if (!new Email("Ana@Example.com ").equals(new Email("ana@example.com"))) throw new AssertionError();
// An entity stays the same entity when its attributes change...
Customer before = new Customer("c-42", new Email("ana@example.com"));
Set<Customer> seen = new HashSet<>(Set.of(before));
before.changeEmail(new Email("ana@work.example"));
if (!seen.contains(before)) throw new AssertionError("hash must depend on id only");
// ...and two different entities with identical attributes are still two entities.
Customer twinA = new Customer("c-1", new Email("same@example.com"));
Customer twinB = new Customer("c-2", new Email("same@example.com"));
if (twinA.equals(twinB)) throw new AssertionError();
System.out.println("equality checks passed");
}
}
from dataclasses import dataclass
@dataclass(frozen=True)
class Email:
value: str
def __post_init__(self) -> None:
if "@" not in self.value:
raise ValueError(f"not an email: {self.value}")
# frozen dataclass: normalise through object.__setattr__
object.__setattr__(self, "value", self.value.strip().lower())
class Customer:
def __init__(self, customer_id: str, email: Email) -> None:
self.id = customer_id
self.email = email
def change_email(self, email: Email) -> None:
self.email = email
def __eq__(self, other: object) -> bool:
return isinstance(other, Customer) and other.id == self.id
def __hash__(self) -> int:
return hash(self.id)
assert Email("Ana@Example.com ") == Email("ana@example.com")
before = Customer("c-42", Email("ana@example.com"))
seen = {before}
before.change_email(Email("ana@work.example"))
assert before in seen
assert Customer("c-1", Email("same@example.com")) != Customer("c-2", Email("same@example.com"))
print("equality checks passed")
// TypeScript has no operator overloading, so value equality is an explicit method.
class Email {
readonly value: string;
constructor(raw: string) {
if (!raw.includes("@")) throw new Error(`not an email: ${raw}`);
this.value = raw.trim().toLowerCase();
}
equals(other: Email): boolean {
return other.value === this.value;
}
}
class Customer {
constructor(readonly id: string, private email: Email) {}
changeEmail(email: Email): void {
this.email = email;
}
equals(other: Customer): boolean {
return other.id === this.id;
}
}
const x = new Email("Ana@Example.com ");
const y = new Email("ana@example.com");
console.assert(x !== y, "different objects");
if (!x.equals(y)) throw new Error("same value");
// A Map keyed by the object uses reference identity, so key entities by their id instead.
const before = new Customer("c-42", new Email("ana@example.com"));
const byId = new Map<string, Customer>([[before.id, before]]);
before.changeEmail(new Email("ana@work.example"));
if (byId.get("c-42") !== before) throw new Error("lookup by id must survive attribute changes");
if (new Customer("c-1", new Email("s@example.com")).equals(new Customer("c-2", new Email("s@example.com"))))
throw new Error("different ids are different entities");
console.log("equality checks passed");
Language notes that come up in interviews:
- Java: records are the natural value object: final fields, value-based
equalsandhashCode, and a compact constructor for validation and normalisation. For entities, writeequalsandhashCodeon the ID only, and don't let either depend on mutable fields. - Python:
@dataclass(frozen=True)gives value equality, hashing and immutability. For entities, a plain class with__eq__and__hash__on the ID, or@dataclass(eq=False)plus your own methods. A non-frozen dataclass with defaulteq=Trueis the trap: it compares all fields and sets__hash__toNone, so it can't go in a set. - TypeScript:
===compares references,MapandSetkey by reference, and there's no operator overloading. Give value objects anequalsmethod, key collections of entities by their ID string, and make value object fieldsreadonly.
5.2 How to decide
| Question | Entity | Value object |
|---|---|---|
| Does it make sense to ask "is this the same one?" after it changes? | yes | no, a changed value is a different value |
| Would two with identical attributes be two different things? | yes (two members called Sam) | no (two 12.50 EUR) |
| Does it have a lifecycle (created, changed, archived)? | usually | no, it's created and replaced |
| Does the business track it over time? | yes | no |
| Can you share one instance between many owners safely? | no | yes, because it's immutable |
In the studio: Member, Session and Booking are entities. Money, TimeSlot, ClassType, Email and all the ID types are value objects.
ClassType is worth a pause. If the studio edits the price of spin, should past bookings change price? No: a booking should record what was charged at the time, which our Booking.charged does. If the studio needs to manage class types (rename one, retire one, report on it across years), ClassType becomes an entity with an ID. For the interview's scope a value is enough, and saying "I'd promote it to an entity if we need to manage class types" shows you know where the line is.
5.3 Why value objects pay off
The most common modelling smell is primitive obsession: using String, int and double for everything. A method book(String memberId, String sessionId) will one day be called with the arguments swapped, and the compiler won't notice. A price that's a double will be added to a fee in a different currency. A startTime that's a long will be compared with a value in seconds instead of milliseconds.
Value objects fix this by putting the validation and the rules in one place:
- they validate once, in the constructor, so every instance in the system is valid (
Emailalways contains@, aTimeSlotalways has a positive length); - they carry their operations (
Money.pluschecks currencies;TimeSlot.hasStarted(now)is one place to get the comparison right); - they make signatures self-documenting:
book(MemberId, SessionId)can't be called the wrong way round; - they're safe to share because they can't change.
The Tactical Design page has full Money, Email and DateRange value objects in TypeScript with base classes; in an interview, records or frozen dataclasses are enough.
6. Aggregates and invariants
6.1 Start from the invariants
An invariant is a rule that must be true whenever anyone looks at the data. List them before you decide any boundaries. For the studio:
- A session never has more confirmed bookings than its capacity.
- A member holds at most one active booking per session.
- The waitlist is served in order, and a freed seat is offered to the waitlist straight away.
- Nobody books, or cancels, a session that has started.
- A class pack's credits never go below zero.
- A booking's recorded charge equals what the member was actually charged or refunded.
Now ask, for each invariant: which objects must be read and changed together to keep it true? Invariants 1 to 4 involve one session and its bookings. Invariant 5 involves one plan. Invariant 6 involves one booking and one plan.
6.2 Draw the boundary around them
An aggregate is a cluster of objects that must be consistent together, with one entity as its root. Outside code holds references only to the root and changes the cluster only by calling the root's methods, so the root can enforce every invariant. Inside, the parts are free to be simple.
For the studio:
Sessionis an aggregate root, containing itsBookings and its waitlist. Every invariant about seats is enforced bySessionmethods.Bookinghas no public way to change its own status; only the session moves it.Memberis a separate aggregate root, containing itsPlan. The credit invariant is enforced by the plan.
Why not put bookings inside Member instead? Because the seat invariants need all bookings for one session at once, and those belong to many different members. If bookings lived under members, checking capacity would mean reading every member who booked that session, and no single object could enforce the rule. Grouping by the invariant, not by "whose is it", is the key move.
flowchart LR
subgraph SessionAgg["Session aggregate"]
S["Session (root)"]
B1["Booking"]
B2["Booking"]
W["Waitlist"]
S --- B1
S --- B2
S --- W
end
subgraph MemberAgg["Member aggregate"]
M["Member (root)"]
P["Plan"]
M --- P
end
B1 -.->|"memberId only"| M
S -.->|"charges via Billing port"| M
6.3 The rules, interview-sized
The full DDD treatment is in Tactical Design. For an interview, four rules cover nearly everything:
- Only the root is referenced from outside. Nobody outside
Sessionholds aBookingand changes it. (Our code returns bookings for reading, and only the session's methods change them.) - Reference other aggregates by ID.
Bookingholds aMemberId, not aMember. That stops one aggregate from reaching into another's state and makes it clear that member and session are loaded, locked and saved separately. - One aggregate per transaction, where you can. A booking changes the session and charges the member: two aggregates. Our design handles this through a narrow
Billingport that the session calls before it changes anything, so a refused charge leaves the session untouched. In a real system with a database, you'd either accept a short window of inconsistency handled by a compensating action, or keep both in one transaction and say why. Saying this aloud is a strong signal; the domain events page shows the event-based alternative. - Keep aggregates small. The bigger the aggregate, the more conflicts under concurrent use. A
Studioaggregate holding every session would serialise every booking in the building. One aggregate per session means two members booking different sessions never contend.
That last point is also the concurrency answer for this design: the aggregate is the unit of locking. Two members racing for the last seat in a session both go through that session's book; lock it (or version it and retry on conflict) and invariant 1 can't break.
7. Relationships and ownership
Once you have entities and values, each relationship between them needs three decisions.
Who owns whom? Ownership means the owner creates the part, the part can't move to another owner, and deleting the owner deletes the part. It's composition in UML terms. Session owns its bookings: they're created by Session.book, they never move to another session, and they make no sense without it. Member owns its plan. Nothing else in the model is owned.
Which direction? Most relationships only need one direction. Booking knows its member's ID; Member doesn't hold a list of bookings. "Show a member's bookings" is a query across sessions, which keeps Member small and avoids keeping two sides in sync. Add the reverse direction only when a use case needs it often and fast.
By reference or by ID? Inside an aggregate, use object references (Session holds Booking objects). Across aggregates, use IDs (Booking holds MemberId). The rule makes aggregate boundaries visible in the code itself: anything you reach by reference you're allowed to change together; anything you reach by ID needs its own lookup.
Many-to-many relationships hide an entity. Members and sessions are many-to-many: a member books many sessions, a session has many members. The relationship carries data (status, charge, time) and has a lifecycle, which means it's an entity in its own right: Booking. Most LLD problems have one of these, and it's often the most important class: Reservation in a hotel, Loan in a library, Ticket in a parking lot, Enrolment in a school. If you've drawn a many-to-many line, look for the noun that should sit in the middle.
| Relationship | Kind | Direction | Held as |
|---|---|---|---|
| Session → Booking | composition, 1 to 0..* | session to booking | object references |
| Session → waitlist | composition (ordered IDs) | session only | queue of BookingId |
| Session → ClassType, TimeSlot | value attributes | session only | values |
| Booking → Member | association across aggregates | booking to member | MemberId |
| Member → Plan | composition, exactly 1 | member to plan | object reference |
| Plan → DropIn / ClassPack / Unlimited | realization | interface |
8. Enums versus polymorphism
Many models contain a "type" of something: plan type, booking status, vehicle type, discount type. The choice is between an enum (one class, a field says which kind) and polymorphism (a class per kind, sharing an interface). Both are right in different situations.
8.1 The rule
If the kinds differ in data and behaviour, use classes. If they differ only in name, or in a little data with shared rules, use an enum.
More concretely, the signs that an enum should become classes:
- you find yourself writing
switch (plan.type)in more than one place; - each case needs different fields (a class pack has credits and an expiry; drop-in has neither);
- adding a new kind means editing several existing methods instead of adding one class (this is the Open/Closed Principle);
- the requirements say "and we'll add more later".
Signs that an enum is right and classes would be over-engineering:
- the kinds share all their data and differ in at most one small, stable rule;
- the behaviour that depends on the kind lives in another class that has to look at the whole situation (the
Sessiondecides what to do with a booking, based on its status and the time); - the set is closed and genuinely small, like a status lifecycle;
- you need to store, compare and iterate over the values (statuses in a database column, a filter dropdown).
In the studio, Plan is polymorphic: each plan has its own data and answers "what does this cost?" differently, and the studio will add plans (a student discount, a corporate account). BookingStatus is an enum: every booking has the same fields whatever its status, and the rules about status transitions all live in Session, which needs to see the whole picture (the time, the capacity, the waitlist) to apply them. Turning statuses into a ConfirmedBooking/CancelledBooking hierarchy would mean replacing the object on each transition, and would spread the session's seat rules across five classes.
8.2 The middle ground: closed hierarchies with exhaustive switches
Modern Java and TypeScript offer a third option that's often the best fit for "a few kinds with different data, where the behaviour belongs to one place". In Java, a sealed interface of records with a pattern-matching switch; in TypeScript, a discriminated union with a never check. Each kind carries its own data, and the compiler tells you every place to update when a kind is added.
import java.util.List;
public class Shapes {
// 1. A plain enum is right when the kinds share the same data and the same rules.
enum Seat {
STANDARD, PREMIUM, ACCESSIBLE;
boolean bookableOnline() { return this != ACCESSIBLE; } // tiny, stable rule: an enum method is fine
}
// 2. Kinds that carry different data and different behaviour: a sealed interface of records.
sealed interface Discount permits Percent, Fixed, BuyXGetY {}
record Percent(int percent) implements Discount {}
record Fixed(long minorOff) implements Discount {}
record BuyXGetY(int buy, int free) implements Discount {}
// The switch is exhaustive: add a fourth record and this stops compiling until it is handled.
static long apply(Discount d, long unitPriceMinor, int qty) {
long gross = unitPriceMinor * qty;
return switch (d) {
case Percent p -> gross - gross * p.percent() / 100;
case Fixed f -> Math.max(0, gross - f.minorOff());
case BuyXGetY b -> unitPriceMinor * (qty - (qty / (b.buy() + b.free())) * b.free());
};
}
public static void main(String[] args) {
if (Seat.ACCESSIBLE.bookableOnline()) throw new AssertionError();
List<Long> totals = List.of(
apply(new Percent(10), 1000, 3),
apply(new Fixed(500), 1000, 3),
apply(new BuyXGetY(2, 1), 1000, 3));
if (!totals.equals(List.of(2700L, 2500L, 2000L))) throw new AssertionError(totals.toString());
System.out.println(totals + " discount checks passed");
}
}
type Discount =
| { kind: "percent"; percent: number }
| { kind: "fixed"; minorOff: number }
| { kind: "buyXGetY"; buy: number; free: number };
function apply(d: Discount, unitPriceMinor: number, qty: number): number {
const gross = unitPriceMinor * qty;
switch (d.kind) {
case "percent":
return gross - Math.floor((gross * d.percent) / 100);
case "fixed":
return Math.max(0, gross - d.minorOff);
case "buyXGetY":
return unitPriceMinor * (qty - Math.floor(qty / (d.buy + d.free)) * d.free);
default: {
const unhandled: never = d; // compile error here if a new kind is added and not handled
throw new Error(`unknown discount ${JSON.stringify(unhandled)}`);
}
}
}
const totals = [
apply({ kind: "percent", percent: 10 }, 1000, 3),
apply({ kind: "fixed", minorOff: 500 }, 1000, 3),
apply({ kind: "buyXGetY", buy: 2, free: 1 }, 1000, 3),
];
if (totals.join() !== "2700,2500,2000") throw new Error(totals.join());
console.log(totals, "discount checks passed");
The trade-off is the classic expression problem. With an interface and one class per kind (the Plan approach), adding a kind is easy (one new class) and adding an operation is hard (edit every class). With a sealed hierarchy and switches, adding an operation is easy (one new function) and adding a kind means visiting every switch, but the compiler finds them all for you. Pick the axis that the requirements say will change. Plans will grow in number and their operations are stable, so Plan is an interface. If the studio instead expected many new questions about a fixed set of discounts (display text, tax treatment, eligibility), a sealed hierarchy would serve it better.
Python has no compile-time exhaustiveness check by default, but match statements over dataclasses plus a type checker such as mypy with assert_never give a similar effect.
9. Modelling money, time and IDs
These three come up in nearly every LLD problem, and getting them wrong is an instant signal to an experienced interviewer.
9.1 Money
Never use binary floating point for money. float and double store binary fractions, and most decimal fractions (0.10, 0.20) have no exact binary representation. The errors are tiny but they accumulate, and they make equality checks fail.
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Arrays;
public class Split {
/** Splits an amount in minor units into n parts that always add back up to the total. */
static long[] allocate(long totalMinor, int parts) {
long[] out = new long[parts];
long base = totalMinor / parts, remainder = totalMinor % parts;
for (int i = 0; i < parts; i++) out[i] = base + (i < remainder ? 1 : 0);
return out;
}
public static void main(String[] args) {
System.out.println(0.1 + 0.2); // 0.30000000000000004
if (0.1 + 0.2 == 0.3) throw new AssertionError();
// BigDecimal is exact for decimal input, but you must choose a rounding rule when dividing.
BigDecimal third = new BigDecimal("100.00").divide(new BigDecimal("3"), 2, RoundingMode.HALF_EVEN);
if (!third.multiply(new BigDecimal("3")).equals(new BigDecimal("99.99"))) throw new AssertionError("a cent vanished");
long[] shares = allocate(10_000, 3); // 100.00 split three ways
if (!Arrays.equals(shares, new long[]{3334, 3333, 3333})) throw new AssertionError();
if (Arrays.stream(shares).sum() != 10_000) throw new AssertionError();
System.out.println(Arrays.toString(shares) + " split checks passed");
}
}
from decimal import ROUND_HALF_EVEN, Decimal
def allocate(total_minor: int, parts: int) -> list[int]:
"""Split an amount in minor units into parts that always add back up to the total."""
base, remainder = divmod(total_minor, parts)
return [base + (1 if i < remainder else 0) for i in range(parts)]
print(0.1 + 0.2) # 0.30000000000000004
assert 0.1 + 0.2 != 0.3
third = (Decimal("100.00") / 3).quantize(Decimal("0.01"), rounding=ROUND_HALF_EVEN)
assert third * 3 == Decimal("99.99") # a cent vanished
shares = allocate(10_000, 3)
assert shares == [3334, 3333, 3333] and sum(shares) == 10_000
print(shares, "split checks passed")
/** Split an amount in minor units into parts that always add back up to the total. */
function allocate(totalMinor: number, parts: number): number[] {
if (!Number.isSafeInteger(totalMinor)) throw new RangeError("amount must be an integer number of minor units");
const base = Math.floor(totalMinor / parts);
const remainder = totalMinor - base * parts;
return Array.from({ length: parts }, (_, i) => base + (i < remainder ? 1 : 0));
}
console.log(0.1 + 0.2); // 0.30000000000000004
if (0.1 + 0.2 === 0.3) throw new Error("unexpected");
// toFixed hides the error on screen, but the stored number is still wrong.
const total = 0.1 + 0.2;
if (total.toFixed(2) !== "0.30" || total === 0.3) throw new Error("unexpected");
const shares = allocate(10_000, 3);
if (shares.join() !== "3334,3333,3333" || shares.reduce((a, b) => a + b, 0) !== 10_000) throw new Error("bad split");
console.log(shares, "split checks passed");
The rules for an LLD Money type:
- Store an exact amount. Either an integer count of minor units (cents, paise) or a decimal type (
BigDecimal, Python'sDecimal). Integer minor units are simplest and fastest. In JavaScript,numberis exact for integers up to 2^53, which is plenty for minor units in most systems; usebigintor a decimal library beyond that. - Carry the currency.
Money(1250, "EUR"), not1250. Adding EUR to USD must fail loudly. Not every currency has two decimal places (the Japanese yen has none, some currencies have three); Java'sjava.util.Currency.getDefaultFractionDigits()tells you. The examples on this page assume two. - Make it immutable.
plusreturns a newMoney. - Decide rounding explicitly. Division and percentages produce fractions of a cent. Pick a rule (banker's rounding,
HALF_EVEN, is a common default for financial totals) and apply it in one place. - Allocate, don't divide. Splitting 100.00 three ways as
33.33 × 3loses a cent. Allocation hands out the remainder so the parts always sum to the total. This comes up in any bill-splitting or refund-proration problem. - Signs mean something. In the studio, a refund is negative money and a fee is positive, which lets
Booking.chargedsimply accumulate. Decide the sign convention and say it.
9.2 Time
Time causes more subtle bugs than money because it looks simple.
- Distinguish an instant from a local date-time. A session starts at a specific instant (a point on the universal timeline, such as
2026-11-20T18:00Z). A recurring schedule ("every Tuesday at 18:00") is local time in a zone (Europe/Berlin). Store schedules as local time plus a zone, and convert each occurrence to an instant when you create the session. Then daylight-saving changes move the instant correctly, and the class still starts at 18:00 on the wall clock. - Do arithmetic on instants. "12 hours before the start" is
start.minus(12 hours)on an instant. Doing it on local times breaks on the two nights a year when clocks change. - Use proper types. Java:
Instant,ZonedDateTime,LocalDate,Duration. Python: timezone-awaredatetimeandtimedelta(reject naive datetimes in constructors, as ourTimeSlotdoes). TypeScript: untilTemporalis available in your runtime, epoch milliseconds in UTC wrapped in a small type are safer than passingDateobjects around, becauseDateis mutable. - Never read the clock inside domain logic. A method that calls
Instant.now()internally can't be tested at 11:59 or across an expiry boundary without waiting. Passnowin as a parameter, or inject aClock. Every method in our studio model takesnow, which is why the demo can test a late cancellation, an expiry and a check-in window in milliseconds. - Model durations and ranges as values.
TimeSlot(start, length)owns "has it started?" and "when does it end?". Overlap checks belong in the range type too (a.overlaps(b)), which is exactly what a meeting-room or hotel problem needs. - Decide the boundary rules. Is a booking 12 hours before the start exactly on time, or late? Our code says "late if after start minus 12 hours", so exactly 12 hours is free. Write the comparison once, and test the boundary.
9.3 IDs
- Give each ID its own type.
MemberId,SessionIdandBookingIdas records, frozen dataclasses, or TypeScript branded strings. It costs one line each and prevents the swapped-argument bug forever. - Decide who generates them. Domain-generated IDs (UUIDs, or an ID derived from the aggregate as our
BookingIdis) let you create an object fully before saving it. Database-generated sequence numbers mean the object has no ID until it's saved, which complicates equality and events. In an interview, generate in the domain and say so. - Don't use mutable natural keys as identity. Email addresses and phone numbers change. Use a surrogate ID for identity and treat the email as an attribute with a uniqueness rule.
- Don't expose internal sequence numbers where they leak information (how many orders you've had) or can be guessed (enumerating other customers' bookings). Opaque IDs are safer at the boundary.
10. Avoiding anaemic models
An anaemic domain model has classes that hold data, with getters and setters, and services that hold all the rules. It looks object-oriented on a diagram and is procedural in practice. Object-Oriented Programming describes the anti-pattern; here's what it costs in a model.
from dataclasses import dataclass, field
# ---- Anaemic: the class is a bag of fields, the rules live in a service ----
@dataclass
class CartA:
items: dict[str, int] = field(default_factory=dict)
checked_out: bool = False
class CartServiceA:
MAX_QTY = 10
def add(self, cart: CartA, sku: str, qty: int) -> None:
if cart.checked_out:
raise ValueError("cart is closed")
if qty < 1 or cart.items.get(sku, 0) + qty > self.MAX_QTY:
raise ValueError("bad quantity")
cart.items[sku] = cart.items.get(sku, 0) + qty
broken = CartA()
CartServiceA().add(broken, "tea", 2)
broken.items["tea"] = 99 # nothing stops this: the rule only holds if every caller goes through the service
assert broken.items["tea"] == 99
# ---- Rich: the object guards its own rules ----
class Cart:
MAX_QTY = 10
def __init__(self) -> None:
self._items: dict[str, int] = {}
self._checked_out = False
def add(self, sku: str, qty: int) -> None:
if self._checked_out:
raise ValueError("cart is closed")
if qty < 1 or self._items.get(sku, 0) + qty > self.MAX_QTY:
raise ValueError("bad quantity")
self._items[sku] = self._items.get(sku, 0) + qty
def check_out(self) -> dict[str, int]:
if not self._items:
raise ValueError("cart is empty")
self._checked_out = True
return dict(self._items) # a copy, so callers cannot edit the cart through it
def quantity(self, sku: str) -> int:
return self._items.get(sku, 0)
cart = Cart()
cart.add("tea", 2)
snapshot = cart.check_out()
snapshot["tea"] = 99
assert cart.quantity("tea") == 2
try:
cart.add("tea", 1)
raise AssertionError("closed cart accepted an item")
except ValueError:
pass
print("anaemic vs rich checks passed")
The two versions contain the same rule. The difference is who can break it. In the anaemic version, the rule holds only if every caller, now and in future, goes through the service. In the rich version, the only way to change the cart is through methods that enforce the rule, and even the returned snapshot is a copy.
Signs your model is anaemic:
- most classes have only getters and setters;
- the services have names like
BookingManager,SessionHelper,OrderProcessorand contain all theifstatements; - the same validation appears in two services;
- tests for business rules need the whole service with mocks, instead of just constructing an object and calling a method.
Services aren't bad in themselves. There are two kinds that belong in a good model:
- Application services coordinate a use case: load the aggregates, call one method on each, save, and trigger side effects such as notifications. They contain no business rules. Our
StudioServiceis one: each method is one or two lines. - Domain services hold a rule that genuinely belongs to no single entity, usually because it spans several (a transfer between two accounts, a pricing rule combining a cart and a customer's loyalty tier). The test: is there an entity that has all the information? If yes, the rule belongs there.
The Common LLD Mistakes page lists anaemic models alongside god classes, which are the opposite failure: one object that knows and does everything.
11. The worked example: text to code
Here's the studio taken all the way through.
11.1 From text to entity list
Sections 3 to 9 produced this list.
| Concept | Kind | Key data | Key behaviour |
|---|---|---|---|
Session | entity, aggregate root | type, slot, capacity, bookings, waitlist | book, cancel, checkIn, revenue |
Booking | entity inside Session | ID, member ID, status, amount charged | none public: changed only by Session |
BookingStatus | enum | confirmed, waitlisted, checked in, cancelled, late-cancelled | isActive, holdsSeat |
Member | entity, aggregate root | ID, name, plan | delegates charging to its plan, changePlan |
Plan | interface | chargeBooking, settleCancellation | |
DropIn, ClassPack, Unlimited | plan implementations | credits and expiry, or validity and late fee | the cost and refund rules |
Money | value object | minor units, currency | plus, negate, currency check |
TimeSlot | value object | start instant, length | end, hasStarted |
ClassType | value object | name, price | |
MemberId, SessionId, BookingId | value objects | a string | equality |
Billing | port (interface) | lets Session charge members without holding them | |
StudioService | application service | maps of members and sessions, notifier | coordinates use cases, implements Billing |
11.2 Class diagram
classDiagram
direction LR
class StudioService {
+book(MemberId m, SessionId s, Instant now) Booking
+cancel(SessionId s, BookingId b, Instant now) void
+checkIn(SessionId s, BookingId b, Instant now) void
}
class Billing {
<<interface>>
+chargeBooking(MemberId m, Money price, Instant now) Money
+settleCancellation(MemberId m, Money price, bool late) Money
}
class Session {
<<aggregate root>>
-SessionId id
-ClassType type
-TimeSlot slot
-int capacity
-Deque~BookingId~ waitlist
+book(MemberId m, Instant now, Billing b) Booking
+cancel(BookingId id, Instant now, Billing b) List~Booking~
+checkIn(BookingId id, Instant now) void
+revenue() Money
}
class Booking {
-BookingId id
-MemberId memberId
-BookingStatus status
-Money charged
}
class BookingStatus {
<<enumeration>>
CONFIRMED
WAITLISTED
CHECKED_IN
CANCELLED
LATE_CANCELLED
}
class Member {
<<aggregate root>>
-MemberId id
-String name
+chargeBooking(Money price, Instant now) Money
+settleCancellation(Money price, bool late) Money
+changePlan(Plan p) void
}
class Plan {
<<interface>>
+chargeBooking(Money price, Instant now) Money
+settleCancellation(Money price, bool late) Money
}
class DropIn
class ClassPack {
-int credits
-Instant expiresAt
}
class Unlimited {
-Instant validUntil
-Money lateFee
}
class Money {
<<value object>>
-long minor
-String currency
+plus(Money other) Money
+negate() Money
}
class TimeSlot {
<<value object>>
-Instant start
-Duration length
+hasStarted(Instant now) bool
}
class ClassType {
<<value object>>
-String name
-Money price
}
Billing <|.. StudioService
StudioService --> "*" Session
StudioService --> "*" Member
Session ..> Billing : charges through
Session "1" *-- "0..*" Booking : owns
Session --> ClassType
Session --> TimeSlot
Booking --> BookingStatus
Booking ..> Member : by MemberId
Member "1" *-- "1" Plan
Plan <|.. DropIn
Plan <|.. ClassPack
Plan <|.. Unlimited
The dashed Booking ..> Member : by MemberId line is how this diagram shows a reference across an aggregate boundary: the booking knows which member, but holds no object.
11.3 The hardest flow: cancel and promote
sequenceDiagram
actor A as Alice
participant SS as StudioService
participant S as Session
participant M as Member
participant P as Plan
A->>SS: cancel(session, booking, now)
SS->>+S: cancel(booking, now, billing)
S->>S: late = now after start minus 12h
S->>SS: settleCancellation(alice, price, late)
SS->>M: settleCancellation(price, late)
M->>P: settleCancellation(price, late)
P-->>SS: refund or fee
SS-->>S: refund or fee
loop while a seat is free and the waitlist is not empty
S->>SS: chargeBooking(next member, price, now)
alt plan pays
SS-->>S: amount
S->>S: mark booking CONFIRMED
else plan refuses
SS-->>S: BookingRejected
S->>S: mark booking CANCELLED, try next
end
end
S-->>-SS: promoted bookings
SS-)A: (promoted members are notified)
The sequence shows why Billing exists. Session must charge the next waitlisted member as part of its own rule ("fill free seats from the waitlist, skipping anyone who can't pay"), but it doesn't hold Member objects, because members are a separate aggregate. The port gives it exactly the two questions it needs to ask, and nothing more.
11.4 The code
All three versions implement the same model and run the same scenario: a two-seat spin class; Alice (drop-in) and Bob (one-credit pack) take the seats; Dave (an empty pack) and Carol (unlimited) join the waitlist; Alice cancels early and is refunded; Dave is skipped because his pack is empty; Carol is promoted and notified; Carol later cancels late and pays the fee; Bob checks in. Each asserts every step, and each was run (Java 24 with java Studio.java, Python 3.12, and TypeScript 5.8 with tsc --strict then tsx).
import java.math.BigDecimal;
import java.time.Duration;
import java.time.Instant;
import java.util.*;
// ---------- Value objects ----------
record Money(long minor, String currency) {
Money {
Objects.requireNonNull(currency, "currency");
}
static Money of(String amount, String currency) {
// BigDecimal parses "12.50" exactly; longValueExact throws if there are more than 2 decimals
return new Money(new BigDecimal(amount).movePointRight(2).longValueExact(), currency);
}
static Money zero(String currency) { return new Money(0, currency); }
Money plus(Money other) {
requireSameCurrency(other);
return new Money(Math.addExact(minor, other.minor), currency);
}
Money negate() { return new Money(Math.negateExact(minor), currency); }
private void requireSameCurrency(Money other) {
if (!currency.equals(other.currency)) {
throw new IllegalArgumentException("currency mismatch: " + currency + " vs " + other.currency);
}
}
@Override public String toString() { return BigDecimal.valueOf(minor, 2).toPlainString() + " " + currency; }
}
record MemberId(String value) {}
record SessionId(String value) {}
record BookingId(String value) {}
record TimeSlot(Instant start, Duration length) {
TimeSlot {
if (length.isNegative() || length.isZero()) throw new IllegalArgumentException("length must be positive");
}
Instant end() { return start.plus(length); }
boolean hasStarted(Instant now) { return !now.isBefore(start); }
}
record ClassType(String name, Money price) {}
// ---------- Plans: behaviour differs per kind, so they are classes, not an enum ----------
class BookingRejected extends RuntimeException {
BookingRejected(String message) { super(message); }
}
interface Plan {
/** Amount charged now for a confirmed spot. Throws BookingRejected if the plan cannot cover it. */
Money chargeBooking(Money price, Instant now);
/** Amount charged now for a cancellation. Negative means a refund. */
Money settleCancellation(Money price, boolean late);
}
class DropIn implements Plan {
public Money chargeBooking(Money price, Instant now) { return price; }
public Money settleCancellation(Money price, boolean late) {
return late ? Money.zero(price.currency()) : price.negate();
}
}
class ClassPack implements Plan {
private int credits;
private final Instant expiresAt;
ClassPack(int credits, Instant expiresAt) { this.credits = credits; this.expiresAt = expiresAt; }
int credits() { return credits; }
public Money chargeBooking(Money price, Instant now) {
if (!now.isBefore(expiresAt)) throw new BookingRejected("class pack expired");
if (credits == 0) throw new BookingRejected("no credits left");
credits--;
return Money.zero(price.currency());
}
public Money settleCancellation(Money price, boolean late) {
if (!late) credits++; // a late cancellation forfeits the credit
return Money.zero(price.currency());
}
}
class Unlimited implements Plan {
private final Instant validUntil;
private final Money lateFee;
Unlimited(Instant validUntil, Money lateFee) { this.validUntil = validUntil; this.lateFee = lateFee; }
public Money chargeBooking(Money price, Instant now) {
if (!now.isBefore(validUntil)) throw new BookingRejected("membership lapsed");
return Money.zero(price.currency());
}
public Money settleCancellation(Money price, boolean late) {
return late ? lateFee : Money.zero(price.currency());
}
}
// ---------- Entities ----------
class Member {
private final MemberId id;
private final String name;
private Plan plan;
Member(MemberId id, String name, Plan plan) { this.id = id; this.name = name; this.plan = plan; }
MemberId id() { return id; }
String name() { return name; }
void changePlan(Plan newPlan) { this.plan = Objects.requireNonNull(newPlan); }
Money chargeBooking(Money price, Instant now) { return plan.chargeBooking(price, now); }
Money settleCancellation(Money price, boolean late) { return plan.settleCancellation(price, late); }
@Override public boolean equals(Object o) { return o instanceof Member m && m.id.equals(id); }
@Override public int hashCode() { return id.hashCode(); }
}
enum BookingStatus {
CONFIRMED, WAITLISTED, CHECKED_IN, CANCELLED, LATE_CANCELLED;
boolean isActive() { return this == CONFIRMED || this == WAITLISTED || this == CHECKED_IN; }
boolean holdsSeat() { return this == CONFIRMED || this == CHECKED_IN; }
}
class Booking {
private final BookingId id;
private final MemberId memberId;
private BookingStatus status;
private Money charged;
Booking(BookingId id, MemberId memberId, BookingStatus status, Money charged) {
this.id = id; this.memberId = memberId; this.status = status; this.charged = charged;
}
BookingId id() { return id; }
MemberId memberId() { return memberId; }
BookingStatus status() { return status; }
Money charged() { return charged; }
// Package-private: only the Session aggregate changes a booking.
void moveTo(BookingStatus next) { this.status = next; }
void addCharge(Money amount) { this.charged = charged.plus(amount); }
@Override public boolean equals(Object o) { return o instanceof Booking b && b.id.equals(id); }
@Override public int hashCode() { return id.hashCode(); }
}
/** The narrow port the Session uses to charge members without holding Member objects. */
interface Billing {
Money chargeBooking(MemberId member, Money price, Instant now);
Money settleCancellation(MemberId member, Money price, boolean late);
}
// ---------- Aggregate root ----------
class Session {
static final Duration FREE_CANCEL_WINDOW = Duration.ofHours(12);
static final Duration CHECK_IN_OPENS = Duration.ofMinutes(30);
private final SessionId id;
private final ClassType type;
private final TimeSlot slot;
private final int capacity;
private final Map<BookingId, Booking> bookings = new LinkedHashMap<>();
private final Deque<BookingId> waitlist = new ArrayDeque<>();
private int sequence = 0;
Session(SessionId id, ClassType type, TimeSlot slot, int capacity) {
if (capacity < 1) throw new IllegalArgumentException("capacity must be at least 1");
this.id = id; this.type = type; this.slot = slot; this.capacity = capacity;
}
SessionId id() { return id; }
ClassType type() { return type; }
Booking book(MemberId member, Instant now, Billing billing) {
if (slot.hasStarted(now)) throw new BookingRejected("session already started");
boolean alreadyBooked = bookings.values().stream()
.anyMatch(b -> b.memberId().equals(member) && b.status().isActive());
if (alreadyBooked) throw new BookingRejected("member already booked on this session");
Booking booking;
if (seatsTaken() < capacity) {
// Charge first: if the plan refuses, nothing in the aggregate has changed.
Money charged = billing.chargeBooking(member, type.price(), now);
booking = new Booking(nextId(), member, BookingStatus.CONFIRMED, charged);
} else {
booking = new Booking(nextId(), member, BookingStatus.WAITLISTED, Money.zero(type.price().currency()));
waitlist.addLast(booking.id());
}
bookings.put(booking.id(), booking);
return booking;
}
/** Cancels a booking and returns the bookings promoted from the waitlist. */
List<Booking> cancel(BookingId bookingId, Instant now, Billing billing) {
Booking booking = find(bookingId);
switch (booking.status()) {
case WAITLISTED -> {
waitlist.remove(bookingId);
booking.moveTo(BookingStatus.CANCELLED);
return List.of();
}
case CONFIRMED -> {
if (slot.hasStarted(now)) throw new BookingRejected("session already started");
boolean late = now.isAfter(slot.start().minus(FREE_CANCEL_WINDOW));
booking.addCharge(billing.settleCancellation(booking.memberId(), type.price(), late));
booking.moveTo(late ? BookingStatus.LATE_CANCELLED : BookingStatus.CANCELLED);
return fillFromWaitlist(now, billing);
}
default -> throw new IllegalStateException("cannot cancel a " + booking.status() + " booking");
}
}
void checkIn(BookingId bookingId, Instant now) {
Booking booking = find(bookingId);
if (booking.status() != BookingStatus.CONFIRMED) throw new IllegalStateException("not a confirmed booking");
boolean open = !now.isBefore(slot.start().minus(CHECK_IN_OPENS)) && now.isBefore(slot.end());
if (!open) throw new IllegalStateException("check-in is closed");
booking.moveTo(BookingStatus.CHECKED_IN);
}
Money revenue() {
Money total = Money.zero(type.price().currency());
for (Booking b : bookings.values()) total = total.plus(b.charged());
return total;
}
int seatsTaken() {
return (int) bookings.values().stream().filter(b -> b.status().holdsSeat()).count();
}
Booking find(BookingId bookingId) {
Booking b = bookings.get(bookingId);
if (b == null) throw new NoSuchElementException("no booking " + bookingId.value());
return b;
}
private List<Booking> fillFromWaitlist(Instant now, Billing billing) {
List<Booking> promoted = new ArrayList<>();
while (seatsTaken() < capacity && !waitlist.isEmpty()) {
Booking next = bookings.get(waitlist.pollFirst());
try {
next.addCharge(billing.chargeBooking(next.memberId(), type.price(), now));
next.moveTo(BookingStatus.CONFIRMED);
promoted.add(next);
} catch (BookingRejected e) {
next.moveTo(BookingStatus.CANCELLED); // their plan cannot pay, so skip to the next person
}
}
return promoted;
}
private BookingId nextId() { return new BookingId(id.value() + "-" + (++sequence)); }
}
// ---------- Application service ----------
interface Notifier { void promoted(Member member, Session session); }
class StudioService implements Billing {
private final Map<MemberId, Member> members = new HashMap<>();
private final Map<SessionId, Session> sessions = new HashMap<>();
private final Notifier notifier;
StudioService(Notifier notifier) { this.notifier = notifier; }
void addMember(Member m) { members.put(m.id(), m); }
void schedule(Session s) { sessions.put(s.id(), s); }
Session session(SessionId id) { return sessions.get(id); }
Booking book(MemberId member, SessionId session, Instant now) {
return sessions.get(session).book(member, now, this);
}
void cancel(SessionId sessionId, BookingId booking, Instant now) {
Session s = sessions.get(sessionId);
for (Booking b : s.cancel(booking, now, this)) notifier.promoted(members.get(b.memberId()), s);
}
void checkIn(SessionId sessionId, BookingId booking, Instant now) { sessions.get(sessionId).checkIn(booking, now); }
public Money chargeBooking(MemberId member, Money price, Instant now) {
return members.get(member).chargeBooking(price, now);
}
public Money settleCancellation(MemberId member, Money price, boolean late) {
return members.get(member).settleCancellation(price, late);
}
}
public class Studio {
static void check(boolean ok, String what) { if (!ok) throw new AssertionError(what); }
public static void main(String[] args) {
List<String> sent = new ArrayList<>();
StudioService studio = new StudioService((m, s) -> sent.add(m.name() + " promoted on " + s.id().value()));
ClassType spin = new ClassType("Spin", Money.of("12.50", "EUR"));
SessionId sid = new SessionId("spin-1120-1800");
studio.schedule(new Session(sid, spin,
new TimeSlot(Instant.parse("2026-11-20T18:00:00Z"), Duration.ofMinutes(45)), 2));
MemberId alice = new MemberId("m-alice"), bob = new MemberId("m-bob");
MemberId carol = new MemberId("m-carol"), dave = new MemberId("m-dave");
ClassPack bobsPack = new ClassPack(1, Instant.parse("2026-12-31T00:00:00Z"));
studio.addMember(new Member(alice, "Alice", new DropIn()));
studio.addMember(new Member(bob, "Bob", bobsPack));
studio.addMember(new Member(carol, "Carol",
new Unlimited(Instant.parse("2026-11-30T00:00:00Z"), Money.of("5.00", "EUR"))));
studio.addMember(new Member(dave, "Dave", new ClassPack(0, Instant.parse("2026-12-31T00:00:00Z"))));
Instant dayBefore = Instant.parse("2026-11-19T09:00:00Z");
Booking a = studio.book(alice, sid, dayBefore);
Booking b = studio.book(bob, sid, dayBefore);
Booking d = studio.book(dave, sid, dayBefore);
Booking c = studio.book(carol, sid, dayBefore);
check(a.status() == BookingStatus.CONFIRMED && a.charged().equals(Money.of("12.50", "EUR")), "alice pays drop-in");
check(b.status() == BookingStatus.CONFIRMED && bobsPack.credits() == 0, "bob uses a credit");
check(d.status() == BookingStatus.WAITLISTED && c.status() == BookingStatus.WAITLISTED, "both waitlisted");
try { studio.book(alice, sid, dayBefore); check(false, "duplicate allowed"); }
catch (BookingRejected expected) { /* one active booking per member */ }
studio.cancel(sid, a.id(), dayBefore); // early: refund, then promote from the waitlist
check(a.status() == BookingStatus.CANCELLED && a.charged().equals(Money.zero("EUR")), "alice refunded");
check(d.status() == BookingStatus.CANCELLED, "dave skipped, no credits");
check(c.status() == BookingStatus.CONFIRMED, "carol promoted");
check(sent.equals(List.of("Carol promoted on spin-1120-1800")), "carol notified");
studio.cancel(sid, c.id(), Instant.parse("2026-11-20T10:00:00Z")); // 8 hours before: late
check(c.status() == BookingStatus.LATE_CANCELLED && c.charged().equals(Money.of("5.00", "EUR")), "late fee");
studio.checkIn(sid, b.id(), Instant.parse("2026-11-20T17:45:00Z"));
check(b.status() == BookingStatus.CHECKED_IN, "bob checked in");
check(studio.session(sid).revenue().equals(Money.of("5.00", "EUR")), "revenue is the late fee");
System.out.println("revenue " + studio.session(sid).revenue() + ", all checks passed");
}
}
from __future__ import annotations
from abc import ABC, abstractmethod
from collections import deque
from dataclasses import dataclass, field
from datetime import datetime, timedelta, timezone
from decimal import Decimal
from enum import Enum
from typing import Callable, Protocol
# ---------- Value objects ----------
@dataclass(frozen=True)
class Money:
minor: int # cents
currency: str
@staticmethod
def of(amount: str, currency: str) -> Money:
cents = Decimal(amount).scaleb(2)
if cents != cents.to_integral_value():
raise ValueError(f"too many decimals: {amount}")
return Money(int(cents), currency)
@staticmethod
def zero(currency: str) -> Money:
return Money(0, currency)
def __add__(self, other: Money) -> Money:
if other.currency != self.currency:
raise ValueError(f"currency mismatch: {self.currency} vs {other.currency}")
return Money(self.minor + other.minor, self.currency)
def __neg__(self) -> Money:
return Money(-self.minor, self.currency)
def __str__(self) -> str:
return f"{Decimal(self.minor).scaleb(-2):.2f} {self.currency}"
@dataclass(frozen=True)
class MemberId:
value: str
@dataclass(frozen=True)
class SessionId:
value: str
@dataclass(frozen=True)
class BookingId:
value: str
@dataclass(frozen=True)
class TimeSlot:
start: datetime
length: timedelta
def __post_init__(self) -> None:
if self.start.tzinfo is None:
raise ValueError("start must be timezone-aware")
if self.length <= timedelta(0):
raise ValueError("length must be positive")
@property
def end(self) -> datetime:
return self.start + self.length
def has_started(self, now: datetime) -> bool:
return now >= self.start
@dataclass(frozen=True)
class ClassType:
name: str
price: Money
# ---------- Plans ----------
class BookingRejected(Exception):
pass
class Plan(ABC):
@abstractmethod
def charge_booking(self, price: Money, now: datetime) -> Money: ...
@abstractmethod
def settle_cancellation(self, price: Money, late: bool) -> Money: ...
class DropIn(Plan):
def charge_booking(self, price: Money, now: datetime) -> Money:
return price
def settle_cancellation(self, price: Money, late: bool) -> Money:
return Money.zero(price.currency) if late else -price
class ClassPack(Plan):
def __init__(self, credits: int, expires_at: datetime) -> None:
self.credits = credits
self._expires_at = expires_at
def charge_booking(self, price: Money, now: datetime) -> Money:
if now >= self._expires_at:
raise BookingRejected("class pack expired")
if self.credits == 0:
raise BookingRejected("no credits left")
self.credits -= 1
return Money.zero(price.currency)
def settle_cancellation(self, price: Money, late: bool) -> Money:
if not late:
self.credits += 1
return Money.zero(price.currency)
class Unlimited(Plan):
def __init__(self, valid_until: datetime, late_fee: Money) -> None:
self._valid_until = valid_until
self._late_fee = late_fee
def charge_booking(self, price: Money, now: datetime) -> Money:
if now >= self._valid_until:
raise BookingRejected("membership lapsed")
return Money.zero(price.currency)
def settle_cancellation(self, price: Money, late: bool) -> Money:
return self._late_fee if late else Money.zero(price.currency)
# ---------- Entities ----------
class Member:
def __init__(self, member_id: MemberId, name: str, plan: Plan) -> None:
self.id = member_id
self.name = name
self._plan = plan
def change_plan(self, plan: Plan) -> None:
self._plan = plan
def charge_booking(self, price: Money, now: datetime) -> Money:
return self._plan.charge_booking(price, now)
def settle_cancellation(self, price: Money, late: bool) -> Money:
return self._plan.settle_cancellation(price, late)
def __eq__(self, other: object) -> bool:
return isinstance(other, Member) and other.id == self.id
def __hash__(self) -> int:
return hash(self.id)
class BookingStatus(Enum):
CONFIRMED = "confirmed"
WAITLISTED = "waitlisted"
CHECKED_IN = "checked_in"
CANCELLED = "cancelled"
LATE_CANCELLED = "late_cancelled"
@property
def is_active(self) -> bool:
return self in (BookingStatus.CONFIRMED, BookingStatus.WAITLISTED, BookingStatus.CHECKED_IN)
@property
def holds_seat(self) -> bool:
return self in (BookingStatus.CONFIRMED, BookingStatus.CHECKED_IN)
@dataclass(eq=False)
class Booking:
id: BookingId
member_id: MemberId
status: BookingStatus
charged: Money
def __eq__(self, other: object) -> bool:
return isinstance(other, Booking) and other.id == self.id
def __hash__(self) -> int:
return hash(self.id)
class Billing(Protocol):
def charge_booking(self, member: MemberId, price: Money, now: datetime) -> Money: ...
def settle_cancellation(self, member: MemberId, price: Money, late: bool) -> Money: ...
# ---------- Aggregate root ----------
class Session:
FREE_CANCEL_WINDOW = timedelta(hours=12)
CHECK_IN_OPENS = timedelta(minutes=30)
def __init__(self, session_id: SessionId, class_type: ClassType, slot: TimeSlot, capacity: int) -> None:
if capacity < 1:
raise ValueError("capacity must be at least 1")
self.id = session_id
self.type = class_type
self._slot = slot
self._capacity = capacity
self._bookings: dict[BookingId, Booking] = {}
self._waitlist: deque[BookingId] = deque()
self._sequence = 0
def book(self, member: MemberId, now: datetime, billing: Billing) -> Booking:
if self._slot.has_started(now):
raise BookingRejected("session already started")
if any(b.member_id == member and b.status.is_active for b in self._bookings.values()):
raise BookingRejected("member already booked on this session")
if self.seats_taken() < self._capacity:
charged = billing.charge_booking(member, self.type.price, now) # may raise: nothing changed yet
booking = Booking(self._next_id(), member, BookingStatus.CONFIRMED, charged)
else:
booking = Booking(self._next_id(), member, BookingStatus.WAITLISTED, Money.zero(self.type.price.currency))
self._waitlist.append(booking.id)
self._bookings[booking.id] = booking
return booking
def cancel(self, booking_id: BookingId, now: datetime, billing: Billing) -> list[Booking]:
booking = self.find(booking_id)
if booking.status is BookingStatus.WAITLISTED:
self._waitlist.remove(booking_id)
booking.status = BookingStatus.CANCELLED
return []
if booking.status is not BookingStatus.CONFIRMED:
raise RuntimeError(f"cannot cancel a {booking.status.value} booking")
if self._slot.has_started(now):
raise BookingRejected("session already started")
late = now > self._slot.start - self.FREE_CANCEL_WINDOW
booking.charged = booking.charged + billing.settle_cancellation(booking.member_id, self.type.price, late)
booking.status = BookingStatus.LATE_CANCELLED if late else BookingStatus.CANCELLED
return self._fill_from_waitlist(now, billing)
def check_in(self, booking_id: BookingId, now: datetime) -> None:
booking = self.find(booking_id)
if booking.status is not BookingStatus.CONFIRMED:
raise RuntimeError("not a confirmed booking")
if not (self._slot.start - self.CHECK_IN_OPENS <= now < self._slot.end):
raise RuntimeError("check-in is closed")
booking.status = BookingStatus.CHECKED_IN
def revenue(self) -> Money:
total = Money.zero(self.type.price.currency)
for b in self._bookings.values():
total = total + b.charged
return total
def seats_taken(self) -> int:
return sum(1 for b in self._bookings.values() if b.status.holds_seat)
def find(self, booking_id: BookingId) -> Booking:
if booking_id not in self._bookings:
raise KeyError(f"no booking {booking_id.value}")
return self._bookings[booking_id]
def _fill_from_waitlist(self, now: datetime, billing: Billing) -> list[Booking]:
promoted: list[Booking] = []
while self.seats_taken() < self._capacity and self._waitlist:
nxt = self._bookings[self._waitlist.popleft()]
try:
nxt.charged = nxt.charged + billing.charge_booking(nxt.member_id, self.type.price, now)
nxt.status = BookingStatus.CONFIRMED
promoted.append(nxt)
except BookingRejected:
nxt.status = BookingStatus.CANCELLED # plan cannot pay, skip to the next person
return promoted
def _next_id(self) -> BookingId:
self._sequence += 1
return BookingId(f"{self.id.value}-{self._sequence}")
# ---------- Application service ----------
class StudioService:
def __init__(self, notify: Callable[[Member, Session], None]) -> None:
self._members: dict[MemberId, Member] = {}
self._sessions: dict[SessionId, Session] = {}
self._notify = notify
def add_member(self, member: Member) -> None:
self._members[member.id] = member
def schedule(self, session: Session) -> None:
self._sessions[session.id] = session
def session(self, session_id: SessionId) -> Session:
return self._sessions[session_id]
def book(self, member: MemberId, session: SessionId, now: datetime) -> Booking:
return self._sessions[session].book(member, now, self)
def cancel(self, session_id: SessionId, booking: BookingId, now: datetime) -> None:
s = self._sessions[session_id]
for b in s.cancel(booking, now, self):
self._notify(self._members[b.member_id], s)
def check_in(self, session_id: SessionId, booking: BookingId, now: datetime) -> None:
self._sessions[session_id].check_in(booking, now)
# Billing protocol
def charge_booking(self, member: MemberId, price: Money, now: datetime) -> Money:
return self._members[member].charge_booking(price, now)
def settle_cancellation(self, member: MemberId, price: Money, late: bool) -> Money:
return self._members[member].settle_cancellation(price, late)
def at(iso: str) -> datetime:
return datetime.fromisoformat(iso).replace(tzinfo=timezone.utc)
if __name__ == "__main__":
sent: list[str] = []
studio = StudioService(lambda m, s: sent.append(f"{m.name} promoted on {s.id.value}"))
spin = ClassType("Spin", Money.of("12.50", "EUR"))
sid = SessionId("spin-1120-1800")
studio.schedule(Session(sid, spin, TimeSlot(at("2026-11-20T18:00"), timedelta(minutes=45)), capacity=2))
alice, bob, carol, dave = (MemberId(f"m-{n}") for n in ("alice", "bob", "carol", "dave"))
bobs_pack = ClassPack(1, at("2026-12-31T00:00"))
studio.add_member(Member(alice, "Alice", DropIn()))
studio.add_member(Member(bob, "Bob", bobs_pack))
studio.add_member(Member(carol, "Carol", Unlimited(at("2026-11-30T00:00"), Money.of("5.00", "EUR"))))
studio.add_member(Member(dave, "Dave", ClassPack(0, at("2026-12-31T00:00"))))
day_before = at("2026-11-19T09:00")
a = studio.book(alice, sid, day_before)
b = studio.book(bob, sid, day_before)
d = studio.book(dave, sid, day_before)
c = studio.book(carol, sid, day_before)
assert a.status is BookingStatus.CONFIRMED and a.charged == Money.of("12.50", "EUR")
assert b.status is BookingStatus.CONFIRMED and bobs_pack.credits == 0
assert d.status is BookingStatus.WAITLISTED and c.status is BookingStatus.WAITLISTED
try:
studio.book(alice, sid, day_before)
raise AssertionError("duplicate allowed")
except BookingRejected:
pass
studio.cancel(sid, a.id, day_before)
assert a.status is BookingStatus.CANCELLED and a.charged == Money.zero("EUR")
assert d.status is BookingStatus.CANCELLED
assert c.status is BookingStatus.CONFIRMED
assert sent == ["Carol promoted on spin-1120-1800"]
studio.cancel(sid, c.id, at("2026-11-20T10:00"))
assert c.status is BookingStatus.LATE_CANCELLED and c.charged == Money.of("5.00", "EUR")
studio.check_in(sid, b.id, at("2026-11-20T17:45"))
assert b.status is BookingStatus.CHECKED_IN
assert studio.session(sid).revenue() == Money.of("5.00", "EUR")
print(f"revenue {studio.session(sid).revenue()}, all checks passed")
// ---------- Value objects ----------
class Money {
private constructor(readonly minor: number, readonly currency: string) {
if (!Number.isSafeInteger(minor)) throw new RangeError(`not a safe integer amount: ${minor}`);
}
static of(amount: string, currency: string): Money {
const m = /^(-?)(\d+)(?:\.(\d{1,2}))?$/.exec(amount);
if (!m) throw new RangeError(`bad amount: ${amount}`);
const cents = Number(m[2]) * 100 + Number((m[3] ?? "0").padEnd(2, "0"));
return new Money(m[1] ? -cents : cents, currency);
}
static zero(currency: string): Money {
return new Money(0, currency);
}
plus(other: Money): Money {
if (other.currency !== this.currency) throw new Error(`currency mismatch: ${this.currency} vs ${other.currency}`);
return new Money(this.minor + other.minor, this.currency);
}
negate(): Money {
return new Money(-this.minor, this.currency);
}
equals(other: Money): boolean {
return this.minor === other.minor && this.currency === other.currency;
}
toString(): string {
const sign = this.minor < 0 ? "-" : "";
const abs = Math.abs(this.minor);
return `${sign}${Math.floor(abs / 100)}.${String(abs % 100).padStart(2, "0")} ${this.currency}`;
}
}
// Branded strings: a MemberId cannot be passed where a SessionId is expected.
type MemberId = string & { readonly __brand: "MemberId" };
type SessionId = string & { readonly __brand: "SessionId" };
type BookingId = string & { readonly __brand: "BookingId" };
const memberId = (v: string) => v as MemberId;
const sessionId = (v: string) => v as SessionId;
// Instants are epoch milliseconds in UTC. Temporal.Instant is the better type once your runtime has it.
type Instant = number;
const MINUTE = 60_000;
const HOUR = 60 * MINUTE;
const at = (iso: string): Instant => Date.parse(iso);
class TimeSlot {
constructor(readonly start: Instant, readonly lengthMs: number) {
if (lengthMs <= 0) throw new RangeError("length must be positive");
}
get end(): Instant {
return this.start + this.lengthMs;
}
hasStarted(now: Instant): boolean {
return now >= this.start;
}
}
interface ClassType {
readonly name: string;
readonly price: Money;
}
// ---------- Plans ----------
class BookingRejected extends Error {}
interface Plan {
chargeBooking(price: Money, now: Instant): Money;
settleCancellation(price: Money, late: boolean): Money;
}
class DropIn implements Plan {
chargeBooking(price: Money): Money {
return price;
}
settleCancellation(price: Money, late: boolean): Money {
return late ? Money.zero(price.currency) : price.negate();
}
}
class ClassPack implements Plan {
constructor(private creditsLeft: number, private readonly expiresAt: Instant) {}
get credits(): number {
return this.creditsLeft;
}
chargeBooking(price: Money, now: Instant): Money {
if (now >= this.expiresAt) throw new BookingRejected("class pack expired");
if (this.creditsLeft === 0) throw new BookingRejected("no credits left");
this.creditsLeft--;
return Money.zero(price.currency);
}
settleCancellation(price: Money, late: boolean): Money {
if (!late) this.creditsLeft++;
return Money.zero(price.currency);
}
}
class Unlimited implements Plan {
constructor(private readonly validUntil: Instant, private readonly lateFee: Money) {}
chargeBooking(price: Money, now: Instant): Money {
if (now >= this.validUntil) throw new BookingRejected("membership lapsed");
return Money.zero(price.currency);
}
settleCancellation(price: Money, late: boolean): Money {
return late ? this.lateFee : Money.zero(price.currency);
}
}
// ---------- Entities ----------
class Member {
constructor(readonly id: MemberId, readonly name: string, private plan: Plan) {}
changePlan(plan: Plan): void {
this.plan = plan;
}
chargeBooking(price: Money, now: Instant): Money {
return this.plan.chargeBooking(price, now);
}
settleCancellation(price: Money, late: boolean): Money {
return this.plan.settleCancellation(price, late);
}
equals(other: Member): boolean {
return other.id === this.id;
}
}
enum BookingStatus {
Confirmed = "CONFIRMED",
Waitlisted = "WAITLISTED",
CheckedIn = "CHECKED_IN",
Cancelled = "CANCELLED",
LateCancelled = "LATE_CANCELLED",
}
const isActive = (s: BookingStatus) =>
s === BookingStatus.Confirmed || s === BookingStatus.Waitlisted || s === BookingStatus.CheckedIn;
const holdsSeat = (s: BookingStatus) => s === BookingStatus.Confirmed || s === BookingStatus.CheckedIn;
class Booking {
constructor(
readonly id: BookingId,
readonly memberId: MemberId,
public status: BookingStatus,
public charged: Money,
) {}
equals(other: Booking): boolean {
return other.id === this.id;
}
}
interface Billing {
chargeBooking(member: MemberId, price: Money, now: Instant): Money;
settleCancellation(member: MemberId, price: Money, late: boolean): Money;
}
// ---------- Aggregate root ----------
class Session {
static readonly FREE_CANCEL_WINDOW = 12 * HOUR;
static readonly CHECK_IN_OPENS = 30 * MINUTE;
private readonly bookings = new Map<BookingId, Booking>();
private readonly waitlist: BookingId[] = [];
private sequence = 0;
constructor(
readonly id: SessionId,
readonly type: ClassType,
private readonly slot: TimeSlot,
private readonly capacity: number,
) {
if (capacity < 1) throw new RangeError("capacity must be at least 1");
}
book(member: MemberId, now: Instant, billing: Billing): Booking {
if (this.slot.hasStarted(now)) throw new BookingRejected("session already started");
for (const b of this.bookings.values()) {
if (b.memberId === member && isActive(b.status)) throw new BookingRejected("member already booked on this session");
}
let booking: Booking;
if (this.seatsTaken() < this.capacity) {
const charged = billing.chargeBooking(member, this.type.price, now); // may throw: nothing changed yet
booking = new Booking(this.nextId(), member, BookingStatus.Confirmed, charged);
} else {
booking = new Booking(this.nextId(), member, BookingStatus.Waitlisted, Money.zero(this.type.price.currency));
this.waitlist.push(booking.id);
}
this.bookings.set(booking.id, booking);
return booking;
}
cancel(bookingId: BookingId, now: Instant, billing: Billing): Booking[] {
const booking = this.find(bookingId);
if (booking.status === BookingStatus.Waitlisted) {
this.waitlist.splice(this.waitlist.indexOf(bookingId), 1);
booking.status = BookingStatus.Cancelled;
return [];
}
if (booking.status !== BookingStatus.Confirmed) throw new Error(`cannot cancel a ${booking.status} booking`);
if (this.slot.hasStarted(now)) throw new BookingRejected("session already started");
const late = now > this.slot.start - Session.FREE_CANCEL_WINDOW;
booking.charged = booking.charged.plus(billing.settleCancellation(booking.memberId, this.type.price, late));
booking.status = late ? BookingStatus.LateCancelled : BookingStatus.Cancelled;
return this.fillFromWaitlist(now, billing);
}
checkIn(bookingId: BookingId, now: Instant): void {
const booking = this.find(bookingId);
if (booking.status !== BookingStatus.Confirmed) throw new Error("not a confirmed booking");
const open = now >= this.slot.start - Session.CHECK_IN_OPENS && now < this.slot.end;
if (!open) throw new Error("check-in is closed");
booking.status = BookingStatus.CheckedIn;
}
revenue(): Money {
let total = Money.zero(this.type.price.currency);
for (const b of this.bookings.values()) total = total.plus(b.charged);
return total;
}
seatsTaken(): number {
let n = 0;
for (const b of this.bookings.values()) if (holdsSeat(b.status)) n++;
return n;
}
find(bookingId: BookingId): Booking {
const b = this.bookings.get(bookingId);
if (!b) throw new Error(`no booking ${bookingId}`);
return b;
}
private fillFromWaitlist(now: Instant, billing: Billing): Booking[] {
const promoted: Booking[] = [];
while (this.seatsTaken() < this.capacity && this.waitlist.length > 0) {
const next = this.find(this.waitlist.shift()!);
try {
next.charged = next.charged.plus(billing.chargeBooking(next.memberId, this.type.price, now));
next.status = BookingStatus.Confirmed;
promoted.push(next);
} catch (e) {
if (!(e instanceof BookingRejected)) throw e;
next.status = BookingStatus.Cancelled; // plan cannot pay, skip to the next person
}
}
return promoted;
}
private nextId(): BookingId {
this.sequence++;
return `${this.id}-${this.sequence}` as BookingId;
}
}
// ---------- Application service ----------
class StudioService implements Billing {
private readonly members = new Map<MemberId, Member>();
private readonly sessions = new Map<SessionId, Session>();
constructor(private readonly notify: (m: Member, s: Session) => void) {}
addMember(m: Member): void {
this.members.set(m.id, m);
}
schedule(s: Session): void {
this.sessions.set(s.id, s);
}
session(id: SessionId): Session {
return this.sessions.get(id)!;
}
book(member: MemberId, session: SessionId, now: Instant): Booking {
return this.session(session).book(member, now, this);
}
cancel(sessionId: SessionId, booking: BookingId, now: Instant): void {
const s = this.session(sessionId);
for (const b of s.cancel(booking, now, this)) this.notify(this.members.get(b.memberId)!, s);
}
checkIn(sessionId: SessionId, booking: BookingId, now: Instant): void {
this.session(sessionId).checkIn(booking, now);
}
chargeBooking(member: MemberId, price: Money, now: Instant): Money {
return this.members.get(member)!.chargeBooking(price, now);
}
settleCancellation(member: MemberId, price: Money, late: boolean): Money {
return this.members.get(member)!.settleCancellation(price, late);
}
}
// ---------- Demo with checks ----------
function check(ok: boolean, what: string): void {
if (!ok) throw new Error(`check failed: ${what}`);
}
const sent: string[] = [];
const studio = new StudioService((m, s) => sent.push(`${m.name} promoted on ${s.id}`));
const spin: ClassType = { name: "Spin", price: Money.of("12.50", "EUR") };
const sid = sessionId("spin-1120-1800");
studio.schedule(new Session(sid, spin, new TimeSlot(at("2026-11-20T18:00:00Z"), 45 * MINUTE), 2));
const [alice, bob, carol, dave] = ["alice", "bob", "carol", "dave"].map((n) => memberId(`m-${n}`));
const bobsPack = new ClassPack(1, at("2026-12-31T00:00:00Z"));
studio.addMember(new Member(alice, "Alice", new DropIn()));
studio.addMember(new Member(bob, "Bob", bobsPack));
studio.addMember(new Member(carol, "Carol", new Unlimited(at("2026-11-30T00:00:00Z"), Money.of("5.00", "EUR"))));
studio.addMember(new Member(dave, "Dave", new ClassPack(0, at("2026-12-31T00:00:00Z"))));
const dayBefore = at("2026-11-19T09:00:00Z");
const a = studio.book(alice, sid, dayBefore);
const b = studio.book(bob, sid, dayBefore);
const d = studio.book(dave, sid, dayBefore);
const c = studio.book(carol, sid, dayBefore);
check(a.status === BookingStatus.Confirmed && a.charged.equals(Money.of("12.50", "EUR")), "alice pays drop-in");
check(b.status === BookingStatus.Confirmed && bobsPack.credits === 0, "bob uses a credit");
check(d.status === BookingStatus.Waitlisted && c.status === BookingStatus.Waitlisted, "both waitlisted");
let rejected = false;
try {
studio.book(alice, sid, dayBefore);
} catch (e) {
rejected = e instanceof BookingRejected;
}
check(rejected, "duplicate rejected");
studio.cancel(sid, a.id, dayBefore);
check(a.status === BookingStatus.Cancelled && a.charged.equals(Money.zero("EUR")), "alice refunded");
check(d.status === BookingStatus.Cancelled, "dave skipped, no credits");
check(c.status === BookingStatus.Confirmed, "carol promoted");
check(sent.length === 1 && sent[0] === "Carol promoted on spin-1120-1800", "carol notified");
studio.cancel(sid, c.id, at("2026-11-20T10:00:00Z"));
check(c.status === BookingStatus.LateCancelled && c.charged.equals(Money.of("5.00", "EUR")), "late fee");
studio.checkIn(sid, b.id, at("2026-11-20T17:45:00Z"));
check(b.status === BookingStatus.CheckedIn, "bob checked in");
check(studio.session(sid).revenue().equals(Money.of("5.00", "EUR")), "revenue is the late fee");
console.log(`revenue ${studio.session(sid).revenue()}, all checks passed`);
11.5 Decisions worth saying aloud
When you present this design, these are the choices an interviewer is likely to probe, and the short answer for each.
- "Why does
Sessiontake aBillingparameter instead of aMember?" Because members are a separate aggregate. The session needs to ask two questions of whoever pays, and the port lets it ask exactly those without being able to change anything else about a member. It also makesSessiontestable with a three-line fake. - "Why charge before creating the booking?" So a refused charge leaves the session untouched. If you create the booking first and the charge fails, you have to undo it, and undo code is where bugs live.
- "Why is
Booking.chargedan accumulated amount instead of a list of payments?" Because the only requirement that uses it is the revenue report, and a running total is enough for that. If the studio needed an audit trail of every charge and refund, I'd replace it with a list of ledger entries and compute the total. - "Why is
BookingStatusan enum butPlanan interface?" Plans differ in data and behaviour, and more will be added. Statuses share all data, and the rules about them need the whole session, so they live inSession. - "Where's the revenue-per-class-type report?"
Session.revenue()gives each session's total. The monthly report is a query that groups sessions by class type and start month and sums them; it doesn't need its own entity. - "What about concurrency?" The session is the unit of consistency, so it's also the unit of locking. Lock per session (or use optimistic versioning with a retry) and two members can never take the last seat. Bookings on different sessions don't contend. Plans need their own guard, because a member could book two sessions at once with one remaining credit; the credit decrement must be atomic too.
11.6 What the interviewer adds next
A model is good if likely extensions change one or two classes. Some typical follow-ups:
| Extension | What changes |
|---|---|
| "Add a 10% student discount on drop-in classes" | A new Plan implementation, or a decorator around DropIn. Nothing else changes |
| "Instructors can't teach overlapping sessions" | Promote instructor to an entity with an ID; a scheduling service checks for overlapping time slots across the instructor's sessions. That's a rule spanning many sessions, so it's a domain service, not a Session method |
| "Waitlisted members must confirm within two hours or lose the spot" | A new OFFERED status and an expiry time on Booking; fillFromWaitlist offers instead of confirming; a sweep expires stale offers. The state diagram grows by one state |
| "No-shows count as late cancellations" | A markNoShows(now) method on Session, run after the session ends, settling each still-CONFIRMED booking as late |
| "Support multiple currencies across studios" | Already safe: Money refuses to mix currencies, so each studio's prices just use its own |
12. Common mistakes
- A class for every noun. Most nouns are attributes. If a class has no behaviour and no identity, fold it into its owner or make it a small value object.
- Subclassing by data.
SpinClass extends ClassType,RedCar extends Car. If the subclasses differ only in field values, use a field. - Subclassing by role.
DropInMember extends Member. Roles change over time; identity doesn't. Give the entity a role or plan object. - Merging synonyms badly or not at all. Two classes for one concept ("Spot" and "Booking"), or one class for two concepts ("Class" for both type and occurrence).
- Grouping by owner instead of by invariant. Putting bookings under
Memberbecause "they're Alice's bookings", when the rules that matter (capacity, waitlist) are per session. - Entities compared by value, values compared by reference. An entity whose hash changes when its email changes vanishes from sets; two equal
Moneyobjects that aren'tequalsbreak every comparison. - Mutable value objects. A
Moneywith asetAmount. Share one between two bookings, change it in one, and the other changes too. - Money as
doubleorfloat. Also: money without a currency, and dividing amounts without an allocation rule. now()inside domain methods. Untestable expiry, cancellation windows and timeouts. Pass time in.- Naive local times for instants. A class at "18:00" with no zone, or deadline arithmetic done on wall-clock time across a daylight-saving change.
- Primitive IDs everywhere.
book(String, String)called with the arguments swapped compiles fine. - Anaemic entities with a manager class. Every rule in
BookingManager, every entity a bag of getters and setters. - A god aggregate.
Studioholding every session, member and booking, so every operation locks everything. - Bidirectional everything.
Member.bookingsandBooking.memberandSession.bookings, all kept in sync by hand. - Modelling the report. A
RevenueReportentity with setters, instead of a query over data the model already records. - Missing the relationship entity. A many-to-many line between
MemberandSessionwith nowhere to put status and charge.
The broader list of LLD interview mistakes, including over-patterning and ignoring concurrency, is in Common LLD Mistakes.
13. Interview questions
Q1. How do you go from a problem statement to a list of classes?
Answer
I list the nouns and verbs, then classify every noun: entity, value object, attribute, actor, synonym, query or out of scope. I merge synonyms and split words used two ways. Then I list the business rules (invariants) and check which objects each rule needs, which tells me where the rules live and where the aggregate boundaries are. The verbs become operations, and each goes to the class that has the information to carry it out. The noun list is only a starting point; classes have to earn their place by owning a rule or a responsibility.
Q2. What's the difference between an entity and a value object? Give an example of something that could be either.
Answer
An entity has an identity that persists while its attributes change, and is compared by ID. A value object is defined entirely by its attributes, is compared by value, and should be immutable. An address can be either: in an online shop it's usually a value (if the customer moves, the new address replaces the old one), but in a postal or utility system an address is an entity with its own ID, because the system tracks things about the property over time.
Q3. What's an aggregate, and how do you choose its boundary?
Answer
A cluster of objects that must stay consistent together, with one root that outside code goes through. I choose the boundary by listing the invariants and grouping the objects each invariant needs. For a class-booking system, "no more confirmed bookings than capacity" needs the session and all its bookings, so the session is the root and bookings are inside it. I keep aggregates as small as the invariants allow, reference other aggregates by ID, and try to change one per transaction, because the aggregate is also the unit of locking.
Q4. When should a switch on a type field become polymorphism?
Answer
When the same switch appears in several places, when the kinds need different fields, or when adding a kind means editing several existing methods. Then each kind becomes a class implementing a shared interface, and adding a kind is adding a class. I'd keep an enum when the kinds share all their data and the behaviour that depends on the kind belongs to another class that sees the whole situation, such as a status whose transitions are decided by an aggregate root. A sealed hierarchy with exhaustive switches is a good middle ground when the set of operations grows more often than the set of kinds.
Q5. Why not use double for money? What do you use instead?
Answer
Binary floating point can't represent most decimal fractions exactly, so 0.1 + 0.2 isn't 0.3, and errors accumulate across many operations and break equality. I use a Money value object holding an integer number of minor units (or a decimal type) plus a currency, immutable, with arithmetic that refuses mixed currencies, an explicit rounding rule for division, and allocation for splits so the parts always sum to the total.
Q6. Your Booking class has getters and setters for everything and BookingService has all the logic. What's wrong, and how would you fix it?
Answer
It's an anaemic model. The rules only hold if every caller goes through the service, the same checks tend to get duplicated, and testing a rule needs the whole service. I'd move each rule to the object that has the data it needs (capacity and waitlist rules into Session, payment rules into Plan), remove the setters so state changes only through methods that enforce the rules, and leave the service with coordination only: load, call one method, save, notify.
Q7. A member can switch from a class pack to unlimited. How does your model handle that?
Answer
The member has a plan rather than being a subtype, so member.changePlan(new Unlimited(...)) replaces the plan object and the member keeps their ID and history. With a ClassPackMember extends Member design, you'd have to create a new member object and migrate every reference to it, which is why roles that change over time should be composed, not inherited. A follow-up worth raising: what happens to the remaining credits? That's a business rule to ask about, not to guess.
Q8. How do you handle "now" in a domain model?
Answer
Never read the system clock inside domain logic. Pass the current instant into methods that need it, or inject a Clock into the service that calls them. That makes time-based rules (cancellation windows, expiry, check-in windows) testable instantly at any boundary. I store instants for points in time, local date-times with a zone for schedules, and do deadline arithmetic on instants so daylight-saving changes don't break it.
Q9. Why reference other aggregates by ID instead of by object?
Answer
It makes the boundary explicit: you can only change what you hold by reference, so one aggregate can't quietly modify another's state and break its invariants. It also means aggregates load, lock and save independently, which keeps transactions small and reduces contention. And it avoids big object graphs that drag half the database into memory.
Q10. Two members try to book the last seat at the same time. Where does your model stop that?
Answer
In the session aggregate. Both requests go through Session.book, which checks capacity and adds the booking in one method. If I lock per session, or store a version number and retry on conflict, only one request can see the free seat. Because each session is its own aggregate, bookings for different sessions don't block each other. The plan's credit counter needs the same treatment, since one member could try to use their last credit on two sessions at once.
Q11. The problem says "the system generates a monthly revenue report". Do you create a Report class?
Answer
Usually not as an entity. A report is a query over data the model already holds. What the model must do is make the report answerable: here, each booking records what was charged, so revenue per class type per month is a group-and-sum over sessions. I'd add a RevenueReport value object for the result if it's useful to pass around, and a reporting service or repository query to produce it.
Q12. How do you know your model is good before writing much code?
Answer
Three checks. Take each business rule from the statement and point to the one method that enforces it. Walk the hardest use case through the class diagram as a sequence of calls, which exposes missing relationships. Then try two likely extensions and count how many classes change; in a good model, it's one or two, and you add classes rather than editing switches.
Related pages
- UML for Interviews: Class, Sequence, State & Activity Diagrams: drawing the model
- Object-Oriented Programming: CRC cards, composition over inheritance, the anaemic model
- OOP Concepts in Depth & UML Class Diagrams
- Domain-Driven Design, especially Tactical Design and Domain Events
- Single Responsibility Principle and Open/Closed Principle
- The LLD Interview Framework and Common LLD Mistakes
- Design Hotel Management System and Movie Booking: the same modelling ideas in case studies
- Low-Level Design Course