Domain-Driven Design (DDD)
Date Published

Domain-Driven Design (DDD)
Domain-Driven Design (DDD) The true value of DDD lies in collaboration and strategic alignment between developers and business experts (Domain Experts) to solve complex problems.
The philosophy of DDD is divided into two major axes: Strategic (how to understand and slice the business) and Tactical (how to code the model with quality).
1. Strategic Axis (The Heart of DDD)
Before writing any line of code, the focus should be on understanding the problem.
- Ubiquitous Language: This is the single, rigorous vocabulary shared between developers and business people. It avoids mental translations or technical jargon in the code; if the expert says "Approve Order," the method in the code should be named exactly
approve_order(). - Subdomains:
- Core Domain: This is the company's competitive advantage, where the essential complexity lies and where the best developers and efforts should focus.
- Supporting Subdomain: Logic necessary to support the business, but which does not bring a differentiator compared to competitors.
- Generic Subdomain: Generic problems that any company has (e.g., billing, email, authentication). The default recommendation is to buy or adopt ready-made solutions instead of building from scratch.
- Bounded Contexts:
- A Bounded Context establishes the explicit boundary within which a domain model is valid and its Ubiquitous Language is consistent.
- Concept of Polysemy: A term such as "Product" means completely different things depending on the context. In the Sales context, it includes price and discount rules; in the Logistics context, it includes only weight, dimensions, and shelf location. Each context should have its own simple, adapted model.
- EventStorming: A visual workshop technique created by Alberto Brandolini where developers and business experts map the process flow using sticky notes with past-tense Domain Events (e.g.,
OrderPlaced,PaymentApproved).
2. Tactical Axis (Application in Code)
Once the model boundary is defined, we use tactical patterns to implement the internal logic:
- Value Objects: Immutable objects without their own identity, defined 100% by their attributes (e.g.,
Money,Address,CPF). Two Value Objects with the same data are identical. - Entities: Objects that have a lifecycle and a unique, persistent identity that remains even if their data changes (e.g., a customer or an order with
order_id). - Aggregates and Aggregate Root:
- An Aggregate is a group of Entities and Value Objects treated as an atomic unit to ensure transactional consistency and business invariants.
- Every change must pass exclusively through the aggregate root (Aggregate Root)[.
- Domain Events: Records of important facts that have already happened in the system (expressed in the past tense). They allow modules to be decoupled and notify other Bounded Contexts asynchronously.
Practical Example in Python (Aggregate + Value Object + Event)
See how to translate an immutable Value Object (Money), an Aggregate Root (Order), and the emission of a Domain Event:
1from dataclasses import dataclass2from decimal import Decimal3from typing import List4 5# 1. Value Object (Immutable and with encapsulated validation)6@dataclass(frozen=True)7class Money:8 amount: Decimal9 currency: str = "BRL"10 11 def add(self, other: "Money") -> "Money":12 if self.currency != other.currency:13 raise ValueError("Cannot add different currencies.")14 return Money(amount=self.amount + other.amount, currency=self.currency)15 16# 2. Domain Event (A fact that has already occurred)17@dataclass(frozen=True)18class OrderPlacedEvent:19 order_id: str20 total_amount: Decimal21 22# 3. Aggregate Root (Guarantees the business rule invariants)23class Order:24 def __init__(self, order_id: str, customer_id: str):25 self.id = order_id26 self.customer_id = customer_id27 self.total = Money(Decimal("0.00"))28 self.status = "DRAFT"29 self.events: List[object] = [] # Facts to be published30 31 def add_item(self, item_price: Money) -> None:32 if self.status != "DRAFT":33 raise ValueError("Cannot modify orders that have already been finalized.")34 self.total = self.total.add(item_price)35 36 def checkout(self) -> None:37 if self.total.amount <= 0:38 raise ValueError("An order must have an amount greater than zero to check out.")39 40 self.status = "PLACED"41 # Emits a domain event to notify other contexts (e.g., Payments)42 self.events.append(OrderPlacedEvent(order_id=self.id, total_amount=self.total.amount))