Skip to content

rrezartprebreza/spring-boot-skills / skills/spring-boot-4/domain-driven-design

domain-driven-design

Verified

Use when evolving aggregate invariants, value objects or domain events in an existing DDD-style Spring Boot 4 application, or when DDD is explicitly requested. Preserve existing API identifiers and architecture when changing domain behavior.

examples/good-aggregate.java

View on GitHub
// GOOD — rich domain model, typed IDs, behavior methods, domain events, no public setters

public class Order {

    private final OrderId id;
    private final CustomerId customerId;
    private final EmailAddress customerEmail;
    private final Currency currency;
    private OrderStatus status;
    private Money total;
    private final List<OrderItem> items = new ArrayList<>();
    @Transient
    private final List<Object> domainEvents = new ArrayList<>();

    private Order(OrderId id, CustomerId customerId, EmailAddress customerEmail, Currency currency) {
        this.id = Objects.requireNonNull(id);
        this.customerId = Objects.requireNonNull(customerId);
        this.customerEmail = Objects.requireNonNull(customerEmail);
        this.currency = Objects.requireNonNull(currency);
        this.status = OrderStatus.DRAFT;
        this.total = Money.zero(currency);
    }

    // Static factory — enforces valid initial state
    public static Order create(CustomerId customerId, EmailAddress email, Currency currency) {
        return new Order(OrderId.generate(), customerId, email, currency);
    }

    // Behavior methods enforce invariants
    public void addItem(ProductId productId, String name, int quantity, Money unitPrice) {
        if (status != OrderStatus.DRAFT)
            throw new OrderNotModifiableException(id);
        if (quantity <= 0)
            throw new InvalidQuantityException(quantity);
        if (!unitPrice.currency().equals(currency))
            throw new CurrencyMismatchException(currency, unitPrice.currency());
        items.add(new OrderItem(productId, name, quantity, unitPrice));
        recalculateTotal();
    }

    public void place() {
        if (items.isEmpty())
            throw new EmptyOrderException(id);
        if (status != OrderStatus.DRAFT)
            throw new IllegalOrderStateTransitionException(status, OrderStatus.PLACED);
        this.status = OrderStatus.PLACED;
        domainEvents.add(OrderPlaced.of(this));
    }

    public void cancel(String reason) {
        if (status == OrderStatus.SHIPPED || status == OrderStatus.DELIVERED)
            throw new IllegalOrderStateTransitionException(status, OrderStatus.CANCELLED);
        this.status = OrderStatus.CANCELLED;
        domainEvents.add(new OrderCancelled(id, customerId, reason, Instant.now()));
    }

    public List<Object> pullDomainEvents() {
        var events = List.copyOf(domainEvents);
        domainEvents.clear();
        return events;
    }

    private void recalculateTotal() {
        this.total = items.stream()
            .map(OrderItem::lineTotal)
            .reduce(Money.zero(currency), Money::add);
    }

    // No public setters — state changes only through behavior methods
    public OrderId getId() { return id; }
    public CustomerId getCustomerId() { return customerId; }
    public OrderStatus getStatus() { return status; }
    public Money getTotal() { return total; }
    public List<OrderItem> getItems() { return Collections.unmodifiableList(items); }
}

// Typed ID — value object
public record OrderId(UUID value) {
    public static OrderId generate() { return new OrderId(UUID.randomUUID()); }
    public static OrderId of(UUID value) { return new OrderId(Objects.requireNonNull(value)); }
}
brainstormingobra/superpowersYou MUST use this before any creative work - creating features, building components, adding functionality, modifying behavior, or planning anything new, in software or out of it (a talk, a business, a renovation).Stars: 322kUpdated Claude CodeCodexVerifiedInstall
brand-guidelinesanthropics/skillsApplies Anthropic's official brand colors and typography to any sort of artifact that may benefit from having Anthropic's look-and-feel. Use it when brand colors or style guidelines, visual formatting, or company design standards apply.Stars: 198kUpdated Claude CodeCodexVerifiedInstall
frontend-designanthropics/skillsGuidance for distinctive, intentional visual design when building new UI or reshaping an existing one. Helps with aesthetic direction, typography, and making choices that don't read as templated defaults.Stars: 198kUpdated Claude CodeCodexVerifiedInstall
mcp-builderanthropics/skillsGuide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when building MCP servers to integrate external APIs or services, whether in Python (FastMCP) or Node/TypeScript (MCP SDK).Stars: 198kUpdated Claude CodeCodexVerifiedInstall