mirror of
https://github.com/hanzoai/skills.git
synced 2026-11-19 00:47:36 +00:00
hanzoskills.com/llms.txt now opens with the install line, the API reference index and the company index, so an agent that lands on any one of the three can find the rest. robots.txt claimed 537 documents while llms.txt counts 920. The number is gone from robots.txt; llms.txt derives it. public/ is regenerated from scripts/site.py, which it had fallen behind: the copy-prompt menu and agent bar were in the generator and not in the committed pages. tests/site.mjs passes against the result. Co-authored-by: Hanzo Dev <[email protected]>
742 lines
32 KiB
HTML
742 lines
32 KiB
HTML
<!doctype html>
|
|
<html lang="en"><head>
|
|
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
|
<title>engineering-domain-driven-design</title>
|
|
<meta name="color-scheme" content="dark">
|
|
<style>
|
|
/* Committed to one visual world: a dark instrument panel. No light variant —
|
|
the dot field and the hairline rules only read on black, and a naive
|
|
inversion would wash both out. Every colour is painted explicitly so the page
|
|
never borrows a host background. */
|
|
@font-face{font-family:'Zen';src:url('/fonts/Zen-Variable.woff2') format('woff2');font-weight:100 900;font-style:normal;font-display:swap}
|
|
@font-face{font-family:'Zen';src:url('/fonts/Zen-Italic-Variable.woff2') format('woff2');font-weight:100 900;font-style:italic;font-display:swap}
|
|
@font-face{font-family:'Zen Mono';src:url('/fonts/ZenMono-Variable.woff2') format('woff2');font-weight:100 900;font-style:normal;font-display:swap}
|
|
@font-face{font-family:'Zen Mono';src:url('/fonts/ZenMono-Italic-Variable.woff2') format('woff2');font-weight:100 900;font-style:italic;font-display:swap}
|
|
@font-face{font-family:'Zen Pixel Square';src:url('/fonts/ZenPixel-Square.woff2') format('woff2');font-style:normal;font-display:swap}
|
|
|
|
:root{
|
|
--ink:#f4f4f2; --soft:#9c9c98; --faint:#6a6a66; --ground:#000; --panel:#0a0a0a;
|
|
--line:#232323; --line-hi:#3a3a3a; --accent:#f4f4f2;
|
|
--font-zen-sans:'Zen',-apple-system,BlinkMacSystemFont,"Segoe UI",Helvetica,Arial,sans-serif;
|
|
--font-zen-mono:'Zen Mono',ui-monospace,"SF Mono",SFMono-Regular,Menlo,Consolas,monospace;
|
|
--font-zen-pixel-square:'Zen Pixel Square',monospace;
|
|
--mono:var(--font-zen-mono);
|
|
--sans:var(--font-zen-sans);
|
|
/* Controls are pills and surfaces are soft, as on hanzo.ai. */
|
|
--r:999px; --r-soft:14px;
|
|
}
|
|
*{box-sizing:border-box}
|
|
html{-webkit-text-size-adjust:100%}
|
|
body{margin:0;background:var(--ground);color:var(--ink);font-family:var(--sans);
|
|
font-size:16px;line-height:1.65;-webkit-font-smoothing:antialiased}
|
|
.wrap{max-width:60rem;margin:0 auto;padding:0 1.75rem}
|
|
|
|
/* The dot field. A halftone made of one repeating radial-gradient, faded out
|
|
along the diagonal by a mask so it reads as a wave rather than wallpaper. */
|
|
/* No overflow clip here: the dot field is inset to the box already, and a clip
|
|
would cut off the copy-prompt menu. */
|
|
.hero{position:relative;border-bottom:1px solid var(--line)}
|
|
.hero::before{content:"";position:absolute;inset:0;
|
|
background-image:radial-gradient(var(--line-hi) 1px, transparent 1px);
|
|
background-size:7px 7px;
|
|
-webkit-mask-image:linear-gradient(115deg,#000 0%,rgba(0,0,0,.55) 38%,transparent 72%);
|
|
mask-image:linear-gradient(115deg,#000 0%,rgba(0,0,0,.55) 38%,transparent 72%);
|
|
pointer-events:none}
|
|
.hero .wrap{position:relative;padding-top:5.5rem;padding-bottom:4rem}
|
|
|
|
nav{border-bottom:1px solid var(--line)}
|
|
nav .in{max-width:60rem;margin:0 auto;padding:1.1rem 1.75rem;display:flex;
|
|
justify-content:space-between;align-items:center;gap:1rem}
|
|
.brand{font-family:var(--mono);font-size:.85rem;letter-spacing:.14em;
|
|
text-transform:uppercase;color:var(--ink);text-decoration:none;
|
|
display:inline-flex;align-items:center;gap:.6rem}
|
|
.brand i{font-style:normal;color:var(--faint)}
|
|
.mark{width:1.15em;height:1.15em;display:block;flex:0 0 auto}
|
|
nav a.up{font-family:var(--mono);font-size:.72rem;letter-spacing:.14em;
|
|
text-transform:uppercase;color:var(--soft);text-decoration:none}
|
|
nav a.up:hover{color:var(--ink)}
|
|
|
|
h1{font-family:var(--mono);font-size:clamp(2rem,5.4vw,3.4rem);line-height:1.12;
|
|
letter-spacing:-.02em;margin:0 0 1.1rem;font-weight:500;text-wrap:balance}
|
|
h1 em{font-style:normal;color:var(--faint)}
|
|
.lede{color:var(--soft);font-size:1.05rem;max-width:52ch;margin:0 0 2.25rem}
|
|
|
|
.btns{display:flex;flex-wrap:wrap;gap:.7rem;margin:0 0 .5rem;align-items:center}
|
|
.btn{display:inline-flex;align-items:center;gap:.5rem;font-family:var(--mono);
|
|
font-size:.72rem;letter-spacing:.14em;text-transform:uppercase;
|
|
padding:.8rem 1.4rem;border:1px solid var(--line-hi);border-radius:var(--r);
|
|
color:var(--ink);text-decoration:none;background:transparent;cursor:pointer;
|
|
line-height:1.2;font-weight:400}
|
|
.btn:hover{background:#141414;text-decoration:none;border-color:var(--soft)}
|
|
.btn.solid{background:var(--ink);color:#000;border-color:var(--ink)}
|
|
.btn.solid:hover{background:#d8d8d4}
|
|
.btn .chev{width:.7em;height:.7em;flex:0 0 auto;transition:transform .15s ease}
|
|
.btn[aria-expanded="true"] .chev{transform:rotate(180deg)}
|
|
|
|
/* Copy-prompt selector. Each row copies the prompt for its own target. */
|
|
.copy{position:relative;display:inline-flex}
|
|
.menu{position:absolute;top:calc(100% + .5rem);left:0;z-index:20;min-width:21rem;
|
|
background:var(--panel);border:1px solid var(--line-hi);border-radius:var(--r-soft);
|
|
padding:.4rem;display:flex;flex-direction:column;
|
|
box-shadow:0 12px 32px rgba(0,0,0,.75)}
|
|
.menu[hidden]{display:none}
|
|
.mi{display:flex;align-items:center;gap:.7rem;width:100%;text-align:left;
|
|
padding:.62rem .8rem;border:0;border-radius:calc(var(--r-soft) - .35rem);
|
|
background:transparent;color:var(--ink);font-family:var(--mono);font-size:.76rem;
|
|
letter-spacing:.04em;text-decoration:none;cursor:pointer;line-height:1.3;
|
|
white-space:nowrap}
|
|
.mi:hover,.mi:focus-visible{background:#181818;outline:none}
|
|
.mi .mark{width:1.05rem;height:1.05rem;color:var(--soft)}
|
|
.mi:hover .mark{color:var(--ink)}
|
|
.mi u{margin-left:auto;color:var(--faint);text-decoration:none;font-size:.68rem;
|
|
letter-spacing:.1em;text-transform:uppercase}
|
|
|
|
/* Works-with bar: one scrolling row, name and mark per agent. */
|
|
.strip{border-bottom:1px solid var(--line);background:var(--panel)}
|
|
.strip .in{max-width:60rem;margin:0 auto;padding:.9rem 1.75rem;display:flex;
|
|
align-items:center;gap:1.25rem;font-family:var(--mono);font-size:.72rem;
|
|
letter-spacing:.1em;text-transform:uppercase;color:var(--faint)}
|
|
.strip b{color:var(--soft);font-weight:400;flex:0 0 auto;
|
|
border-right:1px solid var(--line);padding-right:1.25rem;align-self:stretch;
|
|
display:flex;align-items:center}
|
|
.bar{display:flex;align-items:center;gap:.5rem;flex:1 1 auto;min-width:0;
|
|
overflow-x:auto;scrollbar-width:none;scroll-snap-type:x proximity;
|
|
-webkit-overflow-scrolling:touch;
|
|
-webkit-mask-image:linear-gradient(90deg,#000 calc(100% - 3rem),transparent);
|
|
mask-image:linear-gradient(90deg,#000 calc(100% - 3rem),transparent)}
|
|
.bar::-webkit-scrollbar{display:none}
|
|
.agent{display:inline-flex;align-items:center;gap:.45rem;flex:0 0 auto;
|
|
padding:.4rem .85rem;border:1px solid var(--line);border-radius:var(--r);
|
|
color:var(--soft);white-space:nowrap;scroll-snap-align:start;
|
|
text-decoration:none;background:var(--ground)}
|
|
.agent:hover{color:var(--ink);border-color:var(--line-hi);text-decoration:none}
|
|
.agent .mark{width:.95rem;height:.95rem}
|
|
|
|
h2{font-family:var(--mono);font-size:1.1rem;letter-spacing:-.01em;margin:2.75rem 0 .75rem;font-weight:500}
|
|
h3{font-size:1rem;margin:2rem 0 .5rem;font-weight:600}
|
|
h4,h5,h6{font-size:.94rem;margin:1.5rem 0 .5rem;font-weight:600}
|
|
p{margin:0 0 1rem;max-width:70ch}
|
|
ul,ol{margin:0 0 1rem;padding-left:1.35rem;max-width:70ch}
|
|
li{margin:.22rem 0}
|
|
a{color:var(--ink);text-decoration:underline;text-underline-offset:3px;
|
|
text-decoration-color:var(--line-hi)}
|
|
a:hover{text-decoration-color:var(--ink)}
|
|
a:focus-visible{outline:1px solid var(--ink);outline-offset:3px}
|
|
code{font-family:var(--mono);font-size:.85em;background:var(--panel);
|
|
border:1px solid var(--line);border-radius:5px;padding:.1em .36em}
|
|
pre{background:var(--panel);border:1px solid var(--line);padding:1rem 1.1rem;
|
|
border-radius:var(--r-soft);overflow-x:auto;margin:0 0 1.25rem}
|
|
pre code{background:none;border:0;padding:0;font-size:.82rem;line-height:1.7}
|
|
blockquote{margin:0 0 1rem;padding-left:1rem;border-left:1px solid var(--line-hi);color:var(--soft)}
|
|
hr{border:0;border-top:1px solid var(--line);margin:2.5rem 0}
|
|
table{border-collapse:collapse;width:100%;margin:0 0 1.25rem;font-size:.92rem;
|
|
display:block;overflow-x:auto}
|
|
th,td{border:1px solid var(--line);padding:.5rem .7rem;text-align:left}
|
|
|
|
.curl{display:block;background:var(--panel);border:1px solid var(--line);
|
|
border-radius:var(--r-soft);padding:.95rem 1.1rem;font-family:var(--mono);
|
|
font-size:.8rem;color:var(--soft);overflow-x:auto;margin:0 0 2.5rem;
|
|
white-space:pre;line-height:1.9}
|
|
.curl b{color:var(--ink);font-weight:400}
|
|
.curl i{font-style:normal;color:var(--faint)}
|
|
|
|
/* index */
|
|
#q{width:100%;padding:.85rem 1.2rem;font-family:var(--mono);font-size:.85rem;color:var(--ink);
|
|
background:var(--panel);border:1px solid var(--line);border-radius:var(--r);margin:0 0 .6rem}
|
|
#q::placeholder{color:var(--faint);text-transform:uppercase;letter-spacing:.1em;font-size:.72rem}
|
|
#q:focus{outline:none;border-color:var(--soft)}
|
|
#count{color:var(--faint);font-family:var(--mono);font-size:.72rem;letter-spacing:.1em;
|
|
text-transform:uppercase;margin:0 0 2rem}
|
|
.cat{margin:2.5rem 0 .5rem;font-family:var(--mono);font-size:.7rem;letter-spacing:.16em;
|
|
text-transform:uppercase;color:var(--faint);border-bottom:1px solid var(--line);
|
|
padding-bottom:.45rem}
|
|
.row{display:block;padding:.6rem .9rem;margin:0 -.9rem;border-bottom:1px solid var(--line);
|
|
border-radius:var(--r-soft);text-decoration:none}
|
|
.row:hover{background:#0a0a0a}
|
|
.nm{font-family:var(--mono);font-size:.84rem;color:var(--ink);display:block}
|
|
.ds{color:var(--soft);font-size:.9rem;display:block;margin-top:.12rem}
|
|
footer{margin-top:4rem;padding:2rem 0 4rem;border-top:1px solid var(--line);
|
|
color:var(--faint);font-size:.85rem}
|
|
footer a{color:var(--soft)}
|
|
.fmap{display:grid;gap:1.75rem;grid-template-columns:repeat(auto-fit,minmax(11rem,1fr));
|
|
margin:0 0 2rem;font-size:.85rem}
|
|
.fmap b{display:block;font-family:var(--mono);font-size:.68rem;letter-spacing:.16em;
|
|
text-transform:uppercase;color:var(--faint);font-weight:400;margin:0 0 .6rem;
|
|
border-bottom:1px solid var(--line);padding-bottom:.4rem}
|
|
.fmap a{display:inline-block;color:var(--ink);text-decoration:none;margin:.3rem .35rem 0 0}
|
|
.fmap a:hover{text-decoration:underline}
|
|
.fmap div{color:var(--faint);line-height:1.5}
|
|
.fend{border-top:1px solid var(--line);padding-top:1.25rem;font-size:.82rem}
|
|
|
|
@media (max-width:640px){
|
|
.hero .wrap{padding-top:3.25rem;padding-bottom:2.75rem}
|
|
.btns{gap:.5rem}
|
|
.btn{padding:.75rem 1.15rem;font-size:.68rem}
|
|
.copy,.copy .btn{width:100%;justify-content:center}
|
|
.menu{left:0;right:0;min-width:0}
|
|
.strip .in{flex-direction:column;align-items:flex-start;gap:.6rem;padding:.9rem 1.75rem}
|
|
.strip b{border-right:0;padding-right:0}
|
|
.bar{width:100%}
|
|
}
|
|
</style>
|
|
<link rel="alternate" type="text/markdown" href="/engineering-domain-driven-design.md">
|
|
|
|
<link rel="icon" href="/favicon.svg">
|
|
<link rel="canonical" href="https://hanzoskills.com/engineering-domain-driven-design">
|
|
</head>
|
|
<!-- Reading this with a machine? Every page here is also plain markdown.
|
|
This one: https://hanzoskills.com/engineering-domain-driven-design.md
|
|
Index: https://hanzoskills.com/llms.txt
|
|
Corpus: https://hanzoskills.com/all.md
|
|
Append .md to any path for the markdown twin. -->
|
|
<body>
|
|
<nav><div class="in">
|
|
<a class="brand" href="/"><svg class="mark" viewBox="0 0 67 67" fill="currentColor" aria-hidden="true"><path d="M22.21 67V44.6369H0V67H22.21Z"/><path d="M66.7038 22.3184H22.2534L0.0878906 44.6367H44.4634L66.7038 22.3184Z"/><path d="M22.21 0H0V22.3184H22.21V0Z"/><path d="M66.7198 0H44.5098V22.3184H66.7198V0Z"/><path d="M66.7198 67V44.6369H44.5098V67H66.7198Z"/></svg> HANZO<i>SKILLS</i></a>
|
|
<a class="up" href="/">All skills</a>
|
|
</div></nav>
|
|
|
|
<div class="wrap">
|
|
<h1>engineering-domain-driven-design</h1><p class="lede">Domain-Driven Design patterns, bounded contexts, aggregates, entities, value objects, and strategic design</p><h1>Domain-Driven Design (DDD)</h1>
|
|
<p><strong>Scope</strong>: Comprehensive guide to DDD patterns, strategic design, tactical patterns, and domain modeling <strong>Lines</strong>: ~400 <strong>Last Updated</strong>: 2025-10-27 <strong>Format Version</strong>: 1.0 (Atomic)</p>
|
|
<hr>
|
|
<h2>When to Use This Skill</h2>
|
|
<p>Activate this skill when:</p>
|
|
<ul><li>Building complex business domains with rich logic</li><li>Designing microservices boundaries</li><li>Establishing ubiquitous language with stakeholders</li><li>Modeling enterprise applications</li><li>Refactoring from anemic domain models</li><li>Defining bounded contexts in large systems</li><li>Implementing event-driven architectures</li><li>Collaborating between technical and domain experts</li></ul>
|
|
<h2>Core Concepts</h2>
|
|
<h3>Concept 1: Strategic Design</h3>
|
|
<p><strong>Ubiquitous Language</strong></p>
|
|
<blockquote><p>Shared language between developers and domain experts</p></blockquote>
|
|
<pre><code class="lang-python"># Bad: Technical jargon disconnected from business
|
|
class DataProcessor:
|
|
def execute(self, input_params):
|
|
result = self.algorithm(input_params)
|
|
self.persist(result)
|
|
|
|
# Good: Business language
|
|
class OrderFulfillment:
|
|
def fulfill_order(self, order: Order):
|
|
shipment = self.prepare_shipment(order)
|
|
self.ship_to_customer(shipment)</code></pre>
|
|
<p><strong>Bounded Context</strong></p>
|
|
<blockquote><p>Clear boundary where a model applies</p></blockquote>
|
|
<pre><code>E-commerce System:
|
|
┌─────────────────────┐
|
|
│ Sales Context │ "Customer" = buyer
|
|
│ - Customer │ "Order" = purchase
|
|
│ - Order │
|
|
│ - Product │
|
|
└─────────────────────┘
|
|
|
|
┌─────────────────────┐
|
|
│ Shipping Context │ "Customer" = recipient
|
|
│ - Recipient │ "Order" = shipment
|
|
│ - Shipment │
|
|
│ - Delivery │
|
|
└─────────────────────┘
|
|
|
|
Same words, different meanings in each context!</code></pre>
|
|
<p><strong>Context Map</strong></p>
|
|
<blockquote><p>Relationships between bounded contexts</p></blockquote>
|
|
<pre><code>[Sales Context] ---(Customer/Supplier)---> [Inventory Context]
|
|
↓
|
|
(ACL - Anti-Corruption Layer)
|
|
↓
|
|
[Shipping Context] <---(Shared Kernel)--- [Billing Context]</code></pre>
|
|
<hr>
|
|
<h3>Concept 2: Tactical Patterns - Building Blocks</h3>
|
|
<p><strong>Entity</strong></p>
|
|
<blockquote><p>Object with identity that persists over time</p></blockquote>
|
|
<pre><code class="lang-typescript">class Order {
|
|
private id: OrderId; // Identity
|
|
private customerId: CustomerId;
|
|
private items: OrderItem[];
|
|
private status: OrderStatus;
|
|
private total: Money;
|
|
|
|
// Identity matters - same ID = same order
|
|
equals(other: Order): boolean {
|
|
return this.id.equals(other.id);
|
|
}
|
|
}</code></pre>
|
|
<p><strong>Value Object</strong></p>
|
|
<blockquote><p>Object defined by its attributes, no identity</p></blockquote>
|
|
<pre><code class="lang-python">from dataclasses import dataclass
|
|
|
|
@dataclass(frozen=True) # Immutable
|
|
class Money:
|
|
amount: Decimal
|
|
currency: str
|
|
|
|
def add(self, other: Money) -> Money:
|
|
if self.currency != other.currency:
|
|
raise ValueError("Currency mismatch")
|
|
return Money(self.amount + other.amount, self.currency)
|
|
|
|
# Value objects compared by value, not identity
|
|
money1 = Money(Decimal("10.00"), "USD")
|
|
money2 = Money(Decimal("10.00"), "USD")
|
|
assert money1 == money2 # Equal by value</code></pre>
|
|
<p><strong>Aggregate</strong></p>
|
|
<blockquote><p>Cluster of entities/value objects with a root</p></blockquote>
|
|
<pre><code class="lang-go">// Order Aggregate Root
|
|
type Order struct {
|
|
id OrderID // Identity
|
|
customerID CustomerID
|
|
items []OrderItem // Internal entities
|
|
status OrderStatus
|
|
total Money
|
|
}
|
|
|
|
// Only access OrderItems through Order (aggregate root)
|
|
func (o *Order) AddItem(product Product, quantity int) error {
|
|
if o.status != StatusDraft {
|
|
return errors.New("cannot modify non-draft order")
|
|
}
|
|
|
|
item := NewOrderItem(product, quantity)
|
|
o.items = append(o.items, item)
|
|
o.recalculateTotal() // Invariants maintained by root
|
|
return nil
|
|
}
|
|
|
|
// Aggregate boundary: Order controls access to OrderItems
|
|
// Can't modify OrderItem directly - must go through Order</code></pre>
|
|
<hr>
|
|
<h3>Concept 3: Repositories & Services</h3>
|
|
<p><strong>Repository</strong></p>
|
|
<blockquote><p>Abstraction for collection-like access to aggregates</p></blockquote>
|
|
<pre><code class="lang-typescript">interface OrderRepository {
|
|
findById(id: OrderId): Promise<Order | null>;
|
|
save(order: Order): Promise<void>;
|
|
findByCustomer(customerId: CustomerId): Promise<Order[]>;
|
|
}
|
|
|
|
// Implementation hidden behind interface
|
|
class PostgresOrderRepository implements OrderRepository {
|
|
async findById(id: OrderId): Promise<Order | null> {
|
|
// Database access details hidden
|
|
}
|
|
}</code></pre>
|
|
<p><strong>Domain Service</strong></p>
|
|
<blockquote><p>Operation that doesn't belong to any entity</p></blockquote>
|
|
<pre><code class="lang-python">class PricingService:
|
|
"""Domain service for complex pricing logic"""
|
|
|
|
def calculate_order_total(
|
|
self,
|
|
items: List[OrderItem],
|
|
customer: Customer,
|
|
promotion: Optional[Promotion]
|
|
) -> Money:
|
|
subtotal = sum(item.price for item in items)
|
|
|
|
# Business logic that spans multiple entities
|
|
if customer.is_vip():
|
|
subtotal = subtotal * Decimal("0.9")
|
|
|
|
if promotion:
|
|
subtotal = promotion.apply(subtotal)
|
|
|
|
return Money(subtotal, "USD")</code></pre>
|
|
<hr>
|
|
<h2>Patterns</h2>
|
|
<h3>Pattern 1: Entity vs Value Object</h3>
|
|
<p><strong>Entity Example (Order)</strong>:</p>
|
|
<pre><code class="lang-python">class Order:
|
|
def __init__(self, order_id: OrderId):
|
|
self.id = order_id # Identity
|
|
self.items: List[OrderItem] = []
|
|
self.created_at = datetime.now()
|
|
|
|
def __eq__(self, other):
|
|
return isinstance(other, Order) and self.id == other.id
|
|
|
|
def __hash__(self):
|
|
return hash(self.id)
|
|
|
|
# Same ID = same order, even if attributes differ
|
|
order1 = Order(OrderId("123"))
|
|
order1.items.append(OrderItem("Widget"))
|
|
|
|
order2 = Order(OrderId("123"))
|
|
# order2 has no items, but equals order1 by identity
|
|
assert order1 == order2</code></pre>
|
|
<p><strong>Value Object Example (Address)</strong>:</p>
|
|
<pre><code class="lang-python">@dataclass(frozen=True) # Immutable
|
|
class Address:
|
|
street: str
|
|
city: str
|
|
state: str
|
|
zip_code: str
|
|
|
|
def __post_init__(self):
|
|
if not self.zip_code or len(self.zip_code) != 5:
|
|
raise ValueError("Invalid zip code")
|
|
|
|
# Value objects compared by value
|
|
addr1 = Address("123 Main St", "Boston", "MA", "02101")
|
|
addr2 = Address("123 Main St", "Boston", "MA", "02101")
|
|
assert addr1 == addr2 # Same values = equal
|
|
|
|
# Immutable - create new instance to "change"
|
|
addr3 = Address(addr1.street, "Cambridge", addr1.state, addr1.zip_code)</code></pre>
|
|
<hr>
|
|
<h3>Pattern 2: Aggregate Design</h3>
|
|
<p><strong>Bad: No aggregate boundary</strong>:</p>
|
|
<pre><code class="lang-typescript">// Can modify OrderItem directly - invariants can break!
|
|
const order = orderRepo.findById("123");
|
|
const item = orderItemRepo.findById("456");
|
|
item.quantity = 0; // Violates business rule!
|
|
item.price = -100; // Invalid state!
|
|
orderItemRepo.save(item);</code></pre>
|
|
<p><strong>Good: Aggregate enforces invariants</strong>:</p>
|
|
<pre><code class="lang-typescript">class Order { // Aggregate Root
|
|
private items: OrderItem[] = [];
|
|
|
|
addItem(product: Product, quantity: number): void {
|
|
if (quantity <= 0) {
|
|
throw new Error("Quantity must be positive");
|
|
}
|
|
|
|
const item = new OrderItem(product, quantity);
|
|
this.items.push(item);
|
|
this.recalculateTotal(); // Maintain invariant
|
|
}
|
|
|
|
removeItem(itemId: string): void {
|
|
this.items = this.items.filter(item => item.id !== itemId);
|
|
this.recalculateTotal(); // Maintain invariant
|
|
}
|
|
|
|
private recalculateTotal(): void {
|
|
this.total = this.items.reduce(
|
|
(sum, item) => sum.add(item.subtotal()),
|
|
Money.zero("USD")
|
|
);
|
|
}
|
|
}
|
|
|
|
// Usage: Can only modify through aggregate root
|
|
const order = await orderRepo.findById("123");
|
|
order.addItem(product, 5); // Invariants guaranteed
|
|
await orderRepo.save(order);</code></pre>
|
|
<hr>
|
|
<h3>Pattern 3: Domain Events</h3>
|
|
<pre><code class="lang-python">from dataclasses import dataclass
|
|
from datetime import datetime
|
|
|
|
@dataclass(frozen=True)
|
|
class OrderPlaced:
|
|
"""Domain event: Something that happened in the domain"""
|
|
order_id: str
|
|
customer_id: str
|
|
total: Money
|
|
occurred_at: datetime
|
|
|
|
class Order:
|
|
def __init__(self, order_id: str, customer_id: str):
|
|
self.id = order_id
|
|
self.customer_id = customer_id
|
|
self.items: List[OrderItem] = []
|
|
self.status = OrderStatus.DRAFT
|
|
self._events: List[DomainEvent] = []
|
|
|
|
def place_order(self):
|
|
if not self.items:
|
|
raise ValueError("Cannot place empty order")
|
|
|
|
self.status = OrderStatus.PLACED
|
|
|
|
# Record what happened
|
|
event = OrderPlaced(
|
|
order_id=self.id,
|
|
customer_id=self.customer_id,
|
|
total=self.calculate_total(),
|
|
occurred_at=datetime.now()
|
|
)
|
|
self._events.append(event)
|
|
|
|
def get_events(self) -> List[DomainEvent]:
|
|
return self._events.copy()
|
|
|
|
# Event handlers in other contexts
|
|
class SendConfirmationEmailHandler:
|
|
def handle(self, event: OrderPlaced):
|
|
email_service.send(
|
|
to=get_customer_email(event.customer_id),
|
|
subject="Order Confirmation",
|
|
body=f"Your order {event.order_id} has been placed!"
|
|
)
|
|
|
|
class UpdateInventoryHandler:
|
|
def handle(self, event: OrderPlaced):
|
|
order = order_repo.find(event.order_id)
|
|
for item in order.items:
|
|
inventory.reserve(item.product_id, item.quantity)</code></pre>
|
|
<hr>
|
|
<h3>Pattern 4: Specification Pattern</h3>
|
|
<pre><code class="lang-typescript">// Encapsulate business rules in reusable specifications
|
|
interface Specification<T> {
|
|
isSatisfiedBy(candidate: T): boolean;
|
|
and(other: Specification<T>): Specification<T>;
|
|
or(other: Specification<T>): Specification<T>;
|
|
}
|
|
|
|
class VIPCustomerSpecification implements Specification<Customer> {
|
|
isSatisfiedBy(customer: Customer): boolean {
|
|
return customer.totalPurchases.isGreaterThan(Money.dollars(10000));
|
|
}
|
|
}
|
|
|
|
class RecentCustomerSpecification implements Specification<Customer> {
|
|
isSatisfiedBy(customer: Customer): boolean {
|
|
const daysSinceLastOrder = customer.daysSinceLastOrder();
|
|
return daysSinceLastOrder < 30;
|
|
}
|
|
}
|
|
|
|
// Compose specifications
|
|
const vipSpec = new VIPCustomerSpecification();
|
|
const recentSpec = new RecentCustomerSpecification();
|
|
const eligibleForDiscount = vipSpec.or(recentSpec);
|
|
|
|
if (eligibleForDiscount.isSatisfiedBy(customer)) {
|
|
order.applyDiscount(0.10);
|
|
}</code></pre>
|
|
<hr>
|
|
<h3>Pattern 5: Factory Pattern</h3>
|
|
<pre><code class="lang-python">class OrderFactory:
|
|
"""Create complex aggregates with valid initial state"""
|
|
|
|
def create_order(
|
|
self,
|
|
customer: Customer,
|
|
items: List[Tuple[Product, int]],
|
|
shipping_address: Address
|
|
) -> Order:
|
|
# Validate business rules
|
|
if not customer.is_active():
|
|
raise ValueError("Cannot create order for inactive customer")
|
|
|
|
if not items:
|
|
raise ValueError("Order must have at least one item")
|
|
|
|
# Create aggregate with valid state
|
|
order = Order(
|
|
order_id=OrderId.generate(),
|
|
customer_id=customer.id,
|
|
shipping_address=shipping_address
|
|
)
|
|
|
|
for product, quantity in items:
|
|
if not product.is_available(quantity):
|
|
raise ValueError(f"Product {product.name} not available")
|
|
order.add_item(product, quantity)
|
|
|
|
return order</code></pre>
|
|
<hr>
|
|
<h3>Pattern 6: Anti-Corruption Layer (ACL)</h3>
|
|
<pre><code class="lang-go">// Protect our domain from external system's model
|
|
type ExternalPaymentService struct {
|
|
client *ThirdPartyAPI
|
|
}
|
|
|
|
// External model (we don't control)
|
|
type ThirdPartyPaymentResponse struct {
|
|
TxnID string
|
|
StatusCode int // 1=pending, 2=success, 3=failed
|
|
AmountCents int
|
|
}
|
|
|
|
// Our domain model
|
|
type PaymentResult struct {
|
|
TransactionID string
|
|
Status PaymentStatus // enum: Pending, Completed, Failed
|
|
Amount Money
|
|
}
|
|
|
|
// Anti-Corruption Layer: Translate external model to our model
|
|
func (s *ExternalPaymentService) ProcessPayment(
|
|
amount Money,
|
|
) (PaymentResult, error) {
|
|
// Call external service
|
|
response, err := s.client.Charge(amount.Cents(), amount.Currency())
|
|
if err != nil {
|
|
return PaymentResult{}, err
|
|
}
|
|
|
|
// Translate to our domain model
|
|
return PaymentResult{
|
|
TransactionID: response.TxnID,
|
|
Status: translateStatus(response.StatusCode),
|
|
Amount: Money{Amount: response.AmountCents / 100.0},
|
|
}, nil
|
|
}
|
|
|
|
func translateStatus(code int) PaymentStatus {
|
|
switch code {
|
|
case 1:
|
|
return PaymentStatusPending
|
|
case 2:
|
|
return PaymentStatusCompleted
|
|
case 3:
|
|
return PaymentStatusFailed
|
|
default:
|
|
return PaymentStatusUnknown
|
|
}
|
|
}</code></pre>
|
|
<hr>
|
|
<h2>Best Practices</h2>
|
|
<h3>Modeling Guidelines</h3>
|
|
<p><strong>Entity Design</strong>:</p>
|
|
<ul><li>[ ] Has unique identity</li><li>[ ] Identity persists over time</li><li>[ ] Equality based on ID, not attributes</li><li>[ ] Can change attributes without changing identity</li></ul>
|
|
<p><strong>Value Object Design</strong>:</p>
|
|
<ul><li>[ ] Immutable (cannot change after creation)</li><li>[ ] Equality based on all attributes</li><li>[ ] No identity</li><li>[ ] Can be shared/cached safely</li></ul>
|
|
<p><strong>Aggregate Design</strong>:</p>
|
|
<ul><li>[ ] Has single root entity</li><li>[ ] External objects reference only the root</li><li>[ ] Internal objects not accessible outside</li><li>[ ] Maintains invariants across all contained objects</li><li>[ ] Loaded and saved as a unit</li></ul>
|
|
<hr>
|
|
<h3>Bounded Context Rules</h3>
|
|
<ol><li><strong>Each context has its own model</strong> - Don't share entities across contexts</li><li><strong>Use context maps</strong> - Document relationships between contexts</li><li><strong>Use ACL</strong> - Protect your model from external models</li><li><strong>Published language</strong> - Define contracts between contexts</li><li><strong>Shared kernel</strong> - Minimize shared code between contexts</li></ol>
|
|
<hr>
|
|
<h2>Anti-Patterns</h2>
|
|
<h3>Common DDD Mistakes</h3>
|
|
<pre><code>❌ Anemic Domain Model
|
|
→ Entities with only getters/setters, logic in services
|
|
✅ Rich domain model with behavior in entities
|
|
|
|
❌ Giant Aggregates
|
|
→ Aggregate contains entire object graph
|
|
✅ Small aggregates with clear boundaries
|
|
|
|
❌ Missing Ubiquitous Language
|
|
→ Technical terms disconnected from business
|
|
✅ Code uses business domain terms
|
|
|
|
❌ CRUD-based Design
|
|
→ Thinking in database tables, not domain
|
|
✅ Model business processes and rules
|
|
|
|
❌ Ignoring Bounded Contexts
|
|
→ One model for entire system
|
|
✅ Multiple models with clear boundaries
|
|
|
|
❌ Repository per Entity
|
|
→ Repository for every entity
|
|
✅ Repository per aggregate root only
|
|
|
|
❌ Domain Events as DTOs
|
|
→ Events with no business meaning
|
|
✅ Events capture domain concepts</code></pre>
|
|
<hr>
|
|
<h2>Example: E-Commerce Order</h2>
|
|
<pre><code class="lang-python"># Value Objects
|
|
@dataclass(frozen=True)
|
|
class Money:
|
|
amount: Decimal
|
|
currency: str
|
|
|
|
def add(self, other: Money) -> Money:
|
|
if self.currency != other.currency:
|
|
raise ValueError("Currency mismatch")
|
|
return Money(self.amount + other.amount, self.currency)
|
|
|
|
@dataclass(frozen=True)
|
|
class ProductId:
|
|
value: str
|
|
|
|
# Entity (within Order aggregate)
|
|
class OrderItem:
|
|
def __init__(self, product_id: ProductId, quantity: int, unit_price: Money):
|
|
if quantity <= 0:
|
|
raise ValueError("Quantity must be positive")
|
|
self._product_id = product_id
|
|
self._quantity = quantity
|
|
self._unit_price = unit_price
|
|
|
|
def subtotal(self) -> Money:
|
|
return Money(
|
|
self._unit_price.amount * self._quantity,
|
|
self._unit_price.currency
|
|
)
|
|
|
|
# Aggregate Root
|
|
class Order:
|
|
def __init__(self, order_id: str, customer_id: str):
|
|
self.id = order_id
|
|
self.customer_id = customer_id
|
|
self._items: List[OrderItem] = []
|
|
self._status = OrderStatus.DRAFT
|
|
self._events: List[DomainEvent] = []
|
|
|
|
def add_item(self, product_id: ProductId, quantity: int, unit_price: Money):
|
|
"""Business logic in aggregate root"""
|
|
if self._status != OrderStatus.DRAFT:
|
|
raise ValueError("Cannot modify non-draft order")
|
|
|
|
item = OrderItem(product_id, quantity, unit_price)
|
|
self._items.append(item)
|
|
|
|
def place_order(self):
|
|
"""Business operation"""
|
|
if not self._items:
|
|
raise ValueError("Cannot place empty order")
|
|
|
|
self._status = OrderStatus.PLACED
|
|
self._events.append(OrderPlaced(self.id, datetime.now()))
|
|
|
|
def calculate_total(self) -> Money:
|
|
"""Business logic"""
|
|
return sum(
|
|
(item.subtotal() for item in self._items),
|
|
start=Money(Decimal("0"), "USD")
|
|
)
|
|
|
|
# Repository (only for aggregate roots)
|
|
class OrderRepository(ABC):
|
|
@abstractmethod
|
|
def find_by_id(self, order_id: str) -> Optional[Order]:
|
|
pass
|
|
|
|
@abstractmethod
|
|
def save(self, order: Order) -> None:
|
|
pass
|
|
|
|
# Domain Service
|
|
class OrderFulfillmentService:
|
|
"""Cross-aggregate business logic"""
|
|
|
|
def fulfill_order(self, order: Order, inventory: Inventory):
|
|
for item in order.items:
|
|
if not inventory.is_available(item.product_id, item.quantity):
|
|
raise InsufficientInventoryError()
|
|
|
|
for item in order.items:
|
|
inventory.reserve(item.product_id, item.quantity)
|
|
|
|
order.mark_as_fulfilled()</code></pre>
|
|
<hr>
|
|
<h2>Related Skills</h2>
|
|
<ul><li><strong>engineering-design-patterns</strong>: GoF patterns used in DDD</li><li><strong>engineering-code-quality</strong>: Quality in domain models</li><li><strong>engineering-test-driven-development</strong>: Testing domain logic</li><li><strong>engineering-refactoring-patterns</strong>: Refactoring toward DDD</li><li><strong>api-rest-design</strong>: Designing APIs for bounded contexts</li></ul>
|
|
<hr>
|
|
<h2>References</h2>
|
|
<ul><li><a href="https://www.amazon.com/Domain-Driven-Design-Tackling-Complexity-Software/dp/0321125215">Domain-Driven Design by Eric Evans</a></li><li><a href="https://www.amazon.com/Implementing-Domain-Driven-Design-Vaughn-Vernon/dp/0321834577">Implementing Domain-Driven Design by Vaughn Vernon</a></li><li><a href="https://martinfowler.com/tags/domain%20driven%20design.html">DDD Patterns</a></li><li><a href="https://martinfowler.com/bliki/BoundedContext.html">Bounded Context</a></li></ul>
|
|
<footer>
|
|
<div class="fmap">
|
|
<div><b>Build</b>
|
|
<a href="https://hanzo.app">hanzo.app</a> app builder
|
|
<a href="https://hanzo.codes">hanzo.codes</a> code with an agent
|
|
<a href="https://hanzoskills.com">hanzoskills.com</a> what an agent reads</div>
|
|
<div><b>Run</b>
|
|
<a href="https://console.hanzo.ai">console.hanzo.ai</a> cloud console
|
|
<a href="https://api.hanzo.ai">api.hanzo.ai</a> the API</div>
|
|
<div><b>Account</b>
|
|
<a href="https://hanzo.id">hanzo.id</a> sign in
|
|
<a href="https://pay.hanzo.ai">pay.hanzo.ai</a> top up
|
|
<a href="https://billing.hanzo.ai">billing.hanzo.ai</a> invoices and usage</div>
|
|
<div><b>Company</b>
|
|
<a href="https://hanzo.ai">hanzo.ai</a> canonical
|
|
<a href="https://hanzo.ventures">hanzo.ventures</a> ventures</div>
|
|
</div>
|
|
<div class="fend"><a href="/engineering-domain-driven-design.md">This page as plain text</a> · <a href="/llms.txt">Index for agents</a></div>
|
|
</footer>
|
|
</div></body></html> |