Objects and responsibilities
Assign behavior to the object that owns the relevant state.
Explore the design exercises →
Low Level Design turns a use case into a set of owned state transitions. Start with what a caller may do and what must remain true, then choose objects, relationships and storage. Class names follow those decisions. We will use movie-seat booking to connect object responsibilities to tables, constraints and transactions.
Learning goals
- Identify entities, value objects, services and aggregate boundaries.
- Write preconditions, postconditions and invariants before method bodies.
- Translate object ownership into keys/cardinalities without confusing a class with a table.
What, when, why and how
Use cases and invariants
- what
- A use case names an actor, command and observable success. An invariant is a rule that must survive every accepted transition.
- when
- Before drawing classes or selecting patterns.
- why
- Nouns alone do not tell you which changes must be atomic or what failure means.
- how
- Write the happy path, rejected path and timeout path. For each rule identify the state owner and mutation method. Keep validation before mutation where rollback is avoidable.
Worked example: Hold two seats: either both become owned by the same hold or neither does. A check-then-write across two unrelated owners cannot enforce that contract.
Common mistake: A list of getters/setters with no behavioral contract is a data container, not a complete design.
Entities and value objects
- what
- An entity persists identity across change; a value object is defined by immutable content.
- when
- Choosing equality, ownership and update semantics.
- why
- Using mutable state in hash/equality keys makes identity unstable and can corrupt maps.
- how
- Use stable IDs for entities. Use immutable records for values, validate construction and copy nested mutable collections. Money includes exact amount and currency; a seat coordinate includes its screen context.
Worked example: User U remains the same user after an email change. Money(100,INR) equals another identical value but differs from Money(100,USD).
Common mistake: A Java record does not deep-freeze a supplied List or byte array. Defensive copying must occur at each ownership boundary.
Encapsulation and method contracts
- what
- The owner hides representation and exposes valid operations. A contract states inputs, preconditions, success, rejection and duplicate behavior.
- when
- State has several fields whose relationship matters.
- why
- Public setters allow callers to create combinations the owner would never accept.
- how
- Replace setStatus/setOwner with hold, confirm, expire and cancel. Return immutable snapshots. Validate authorization at the service boundary and domain consistency at the state owner.
Worked example: confirm(holdId,paymentEvidence) must verify identity, amount, expiry and current seat ownership before changing state.
Common mistake: Private fields alone do not protect state if getters return their mutable maps.
Cohesion, services and aggregate ownership
- what
- Cohesion puts behavior near the state it needs; an aggregate is a consistency boundary for related changes. A service coordinates work spanning boundaries.
- when
- Choosing whether a method belongs on Seat, ShowInventory or CheckoutService.
- why
- Tiny objects cannot each enforce an all-seat invariant without a common transaction owner. A giant service becomes hard to reason about.
- how
- Let ShowInventory own competing seat claims within a show. Let Checkout coordinate payment commands and correlated results without holding the inventory lock during network I/O.
Worked example: One ShowInventory reserves a requested seat set atomically; the gateway only translates a provider protocol.
Common mistake: An aggregate is not necessarily every object reachable by a foreign key. Booking, user profile and film catalog need not share one lock.
Keys, relationships and cardinality
- what
- A primary key identifies a row; a foreign key references a parent; cardinality states how many instances may participate.
- when
- Moving from object design to a persistent model.
- why
- A beautiful class diagram does not explain uniqueness, optional ownership or cross-show seat reuse.
- how
- Model Screen 1→many Seat, Movie 1→many Show and Show 1→many ShowSeat. Use unique(show_id,seat_id); BookingOrder→OrderSeat links historical purchased selections. Nullable current owner on ShowSeat is different from historical lines.
Worked example: A12 in the same auditorium can be sold in both the 18:00 and 21:00 shows. Physical seat identity must not imply a global sold flag.
Common mistake: A foreign key to Show and a foreign key to Seat do not prove they belong to the same screen; add composite references or transaction validation.
Persistence projections, constraints and indexes
- what
- Tables preserve identity/facts; projections optimize observation; indexes support declared access patterns.
- when
- Choosing a schema for the object model.
- why
- Duplicated writable truth drifts, and adding an index cannot repair a missing transaction invariant.
- how
- Separate immutable order prices from mutable catalog prices. Document which balance/availability fields are projections. Use unique keys for local row identity and a shared transaction for cross-row conservation.
Worked example: Find show seats by (show_id,seat_id); expire active orders by deadline; view a user order history by (user_id,created_at).
Common mistake: Uniqueness on (show_seat_id) in historical order lines would block legitimate reuse after expired holds. Enforce current ownership separately.
Value validation and defensive copying
Illustrative Java 21 snippet; the linked exercises contain complete executable references and tests.
These package-private Java 21 records are illustrative values. List.copyOf prevents callers changing the requested set after validation; it rejects null elements. It does not establish seat existence, authorization or atomic availability. Those checks belong to the show inventory/service transaction. Currency conversion and negative signed ledger deltas use different contracts from this nonnegative price value.
Worked design exercise
Design the objects and schema for holding two movie seats, then receiving a late payment.
- Identify User, Show, physical Seat, ShowSeat, Hold/Order, OrderSeat and PaymentAttempt.
- Choose ShowInventory as the local all-seat owner; write at-most-one-current-owner invariant.
- Keep immutable order lines and explicit current hold state/deadline.
- Send payment command outside inventory ownership with stable external identity.
- If payment arrives after expiry and seats have another owner, retain charge evidence and create a refund obligation.
Compare your reasoning with the worked answer
Holding changes current ownership atomically; price lines preserve history. A late charge cannot reclaim the seats. The object API and table constraints must express the same boundary, and external refund work needs its own state.
Engineer to Staff follow-ups
Engineer: Why is Seat different from ShowSeat?
Seat is physical layout; ShowSeat is occurrence-specific inventory. Their identities have different lifetimes.
Senior: Should every relationship be loaded into one aggregate?
No. Load the state required to enforce the command invariant. Transaction ownership does not require pulling all user/catalog history into memory.
Staff: What changes when show inventory spans services?
A local lock no longer gives one atomic all-seat decision. Choose a shared transactional authority or explicit partial reservation/saga semantics and expose the trade-off.
Apply it in design exercises
- Movie Ticket Booking: screen, show and order relationships →
- Inventory: allocation ownership and conservation →
For each exercise, derive the object owner, schema keys/relationships and transaction boundary before revealing the reference.