Spring Boot Tutorial 0/110 lessons ~6 min read Lesson 92

    Domain-Driven Design

    Domain-Driven Design is the playbook for complex domains: bounded contexts, aggregates with strong invariants, and domain events.

    Course progress0%
    Focus
    12 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    Introduction

    Domain-Driven Design is the playbook for complex domains: bounded contexts, aggregates with strong invariants, and domain events. TechLearningPRO Orders becomes painful when 'order' means different things to billing, catalog, and support — DDD names those seams explicitly.

    Use DDD where rules are deep (pricing, fulfillment states, refunds). It is overkill for a three-field CRUD form. On Boot 3, aggregates are plain Java; Spring Data repositories load aggregate roots; events publish via Spring or an outbox.

    Ubiquitous language means the same words in code, tests, and standups — PlaceOrder not saveOrderData. Bounded contexts often map later to services, but start as modular packages.

    This lesson gives Orders the DDD vocabulary before cataloguing recurring backend patterns.

    Purpose of this lesson

    Model Orders with bounded contexts, aggregates, value objects, and domain events where complexity warrants DDD.

    Understanding the topic

    Shared vocabulary for complex domains.

    • Bounded context: subdomain with its own model and language.
    • Aggregate: cluster of entities/values guarded by a root.
    • Value object: immutable, equal by value (Money, EmailAddress).
    • Domain event: something meaningful happened (OrderPlaced).
    • Repository: collection-like access to aggregates.
    • Ubiquitous language: same words in code and conversation.

    Step-by-step explanation

    1. Write the Orders ubiquitous language in a one-page glossary with the product owner.
    2. Identify the Order aggregate root and invariants (e.g. non-empty lines, non-negative money).
    3. Model Money as a value object; reject primitive obsession for currency amounts.
    4. Emit OrderPlaced from the aggregate/use case; persist then publish via outbox when reliability matters.

    Informative example

    Order aggregate + Money value object (framework-free domain).

    java
    public final class Money {
    private final long amountCents;
    private final String currency;
    private Money(long amountCents, String currency) {
    if (amountCents < 0) throw new IllegalArgumentException("negative");
    this.amountCents = amountCents;
    this.currency = Objects.requireNonNull(currency);
    }
    public static Money ofCents(long cents, String currency) {
    return new Money(cents, currency);
    }
    public long amountCents() { return amountCents; }
    public String currency() { return currency; }
    }
    public class Order {
    private final OrderId id;
    private final List<OrderLine> lines;
    private OrderStatus status;
    public static Order place(CustomerId customerId, List<OrderLine> lines) {
    if (lines == null || lines.isEmpty()) {
    throw new DomainException("order requires lines");
    }
    Order order = new Order(OrderId.newId(), customerId, List.copyOf(lines), OrderStatus.PLACED);
    order.events.add(new OrderPlaced(order.id));
    return order;
    }
    }

    Real-world use

    Billing called 'order' a payable invoice; warehouse called 'order' a pick list. Without bounded contexts, TechLearningPRO shared one tangled table and shipped wrong refunds. Splitting Billing and Fulfillment models — with events between them — stopped the cross-talk.

    Security implications

    Aggregates enforce invariants that double as safety checks.

    • Reject negative money and empty carts in the domain — not only in the UI.
    • Authorize actions on the aggregate (cancel/refund) with clear roles.
    • Do not put secrets or raw payment tokens inside domain events.

    Best practices

    • Start with language and invariants; add tactical patterns as needed.
    • One transaction per aggregate write; integrate contexts via events.
    • Map bounded contexts to modules first; extract microservices only when forced.

    Common mistakes

    • Applying full DDD ceremony to a trivial CRUD module.
    • Anemic aggregates that are just bags of getters with services holding all rules.
    • Updating child entities without going through the aggregate root.

    Advanced interview questions

    Interview Prep

    Practice concise answers, then expand each card for the explanation.

    3 questions
    1BeginnerQuestionWhat is a bounded context?+

    Answer

    A boundary inside which a particular domain model and ubiquitous language apply consistently.
    2IntermediateQuestionWhy protect invariants in the aggregate root?+

    Answer

    So every write path upholds rules; bypassing the root invites corruption.
    3IntermediateQuestionWhen is DDD overkill?+

    Answer

    Simple CRUD with little business logic — layered Spring services are enough.

    Hands-on exercise

    Lab. Implement Money and Order.place with invariants and an OrderPlaced event list. Unit-test empty lines and negative cents; keep Spring out of the domain module.

    Summary

    DDD gives Orders a precise language and safe aggregates. Next: the backend design patterns you will meet weekly in Spring codebases.

    Ready to mark this lesson complete?Track your journey across the entire course.