Domain-Driven Design: คู่มือฉบับสมบูรณ์¶
คำนี้คุณคงได้ยินมาแล้ว อาจเคยอ่าน blue book ไปสักบทด้วย แต่พอลองเอา DDD มาใช้จริงทีไร ก็รู้สึกเหมือนแค่เปลี่ยนชื่อของเดิม แล้วเรียกว่า architecture
DDD เกิดมาเพื่อแก้ปัญหาอะไร¶
ก่อนลงไปที่ pattern กับศัพท์ต่าง ๆ มาดูก่อนว่าปัญหาจริงอยู่ตรงไหน
สมมติคุณเพิ่งเข้าบริษัทที่มี e-commerce monolith อายุห้าปี ในระบบมี class User อยู่สาม module ตัวแรกหมายถึงลูกค้า ตัวที่สองหมายถึง admin ตัวที่สามหมายถึงผู้ขาย ตาราง Order มี 47 column ส่วนฟังก์ชัน process_payment() ยาว 600 บรรทัด ไม่มีใครกล้าแตะ หน้าตาแบบนี้แหละคือ Big Ball of Mud ซอฟต์แวร์ที่โตไปเรื่อย ๆ โดยไม่มีใครเข้าใจธุรกิจตรงกัน สุดท้ายก็จบแบบนี้
ต้นเหตุไม่ได้อยู่ที่โค้ดแย่ แต่อยู่ที่ ช่องว่างระหว่างคนที่เข้าใจธุรกิจกับคนที่เขียนโค้ด Domain-Driven Design มาเพื่อปิดช่องว่างนี้
Eric Evans, Domain-Driven Design (2003)
"The heart of software is its ability to solve domain-related problems for its users. All other features, vital as they may be, support this basic purpose."
Domain-Driven Design คืออะไร¶
DDD เป็นแนวคิดในการพัฒนาซอฟต์แวร์ ไม่ใช่ framework หัวใจคือเอา business domain ไว้ตรงกลาง แล้วตัดสินใจเรื่อง design ทุกอย่างโดยยึด domain เป็นหลัก สิ่งที่ได้คือ:
- ภาษากลางที่ developer กับคนฝั่งธุรกิจใช้ตรงกัน
- เส้นแบ่งที่ชัดเจนระหว่างแต่ละส่วนของระบบ
- Pattern สำหรับเขียน business logic ที่ซับซ้อนออกมาเป็นโค้ด
DDD แบ่งการคิดเป็นสองระดับ:
| ระดับ | โฟกัส | ตอบคำถามอะไร |
|---|---|---|
| Strategic Design | ภาพใหญ่ — โครงสร้างของระบบ | เราสร้างอะไร และแต่ละชิ้นเกี่ยวกันยังไง |
| Tactical Design | ระดับโค้ด — เขียน logic ยังไง | โค้ดข้างในแต่ละชิ้นควรเขียนยังไง |
พูดง่าย ๆ คือ Strategic Design เป็นแผนที่ ส่วน Tactical Design เป็นวิธีขับไปบนถนนแต่ละเส้น
ภาค 1: Strategic Design¶
Strategic design คือการทำความเข้าใจภาพรวมธุรกิจให้ได้ก่อนเขียนโค้ดบรรทัดแรก โปรเจกต์ DDD ส่วนใหญ่พังเพราะข้ามขั้นนี้ไป
ขั้นที่ 1: รู้จัก Domain ของตัวเอง¶
Domain ก็คือเรื่องที่ซอฟต์แวร์ของคุณดูแลอยู่ ธนาคารก็มี domain เป็นงานธนาคาร บริษัท e-commerce ก็คือค้าปลีกออนไลน์
ไม่มี domain ไหนที่ทุกส่วนสำคัญเท่ากัน บางส่วนสำคัญกว่าส่วนอื่นเสมอ DDD เลยแบ่ง domain ออกเป็นสามแบบ:
┌─────────────────────────────────────┐
│ YOUR DOMAIN │
│ │
│ ┌──────────┐ ┌──────────────┐ │
│ │ CORE │ │ SUPPORTING │ │
│ │ DOMAIN │ │ DOMAIN │ │
│ │ │ │ │ │
│ │ This is │ │ Enables your │ │
│ │ your │ │ core — but │ │
│ │ secret │ │ not unique │ │
│ │ sauce │ │ to you │ │
│ └──────────┘ └──────────────┘ │
│ │
│ ┌─────────────────┐ │
│ │ GENERIC DOMAIN │ │
│ │ │ │
│ │ Buy it, don't │ │
│ │ build it │ │
│ └─────────────────┘ │
└─────────────────────────────────────┘
Core Domain¶
Core Domain คือเหตุผลที่บริษัทคุณมีอยู่ เป็น ความได้เปรียบในการแข่งขัน คือสิ่งที่คุณทำได้ดีกว่าใคร ตรงนี้ควรลงทุนหนักและเขียนซอฟต์แวร์เอง
- Amazon: Recommendation engine + fulfillment logistics
- Netflix: อัลกอริทึมแนะนำ content
- Uber: Ride-matching และ dynamic pricing
อย่า outsource Core Domain เด็ดขาด
ซื้อ CRM สำเร็จรูปมา customize ให้เป็น core domain เป็นความผิดพลาดที่เจอบ่อยและเสียเงินเยอะ ถ้าคู่แข่งซื้อซอฟต์แวร์ตัวเดียวกันได้ ก็เอามาสร้างความต่างให้คุณไม่ได้
Supporting Domain¶
จำเป็นต้องมี แต่ไม่ได้ทำให้คุณต่างจากคนอื่น Supporting domain ช่วยหนุน core ก็จริง แต่ลูกค้าไม่ได้เลือกคุณเพราะส่วนนี้ อาจยังต้องเขียนโค้ดเอง แต่ไม่ต้องเอา engineer มือดีที่สุดมาลงตรงนี้
- inventory management ของบริษัท e-commerce คือ supporting — Amazon ก็มี Shopify ก็มี ร้านค้าปลีกทุกเจ้าก็มี
Generic Domain¶
ฟังก์ชันพื้นฐานที่มีของสำเร็จรูปขายอยู่แล้ว ส่วนนี้ซื้อ สมัคร subscription หรือใช้ open-source ไปเลย
- Email delivery → SendGrid, SES
- Authentication → Auth0, Cognito
- Payments → Stripe, PayPal
ทีมควรทุ่มแรงตรงไหน
ทุ่มเต็มที่กับ Core ลงแรงกับ Generic ให้น้อยที่สุด (ซื้อหรือ outsource) ส่วน Supporting ทำให้ดีพอใช้ก็พอ
ขั้นที่ 2: Ubiquitous Language — ภาษาเดียวที่ทุกคนใช้ตรงกัน¶
ใน DDD ไม่มี concept ไหนโดนมองข้ามเท่าเรื่องนี้ ก่อนเขียนโค้ดสักบรรทัด ทีม dev กับ stakeholder ฝั่งธุรกิจต้อง ตกลงคำศัพท์ชุดเดียวกันให้ได้ก่อน
ปัญหาคือคำเดียวกัน แต่ละคนเข้าใจไม่เหมือนกัน:
| คำ | developer เข้าใจว่า | business analyst หมายถึง |
|---|---|---|
User | แถวหนึ่งในตาราง users | คนที่ login เข้ามา |
Account | record ใน database ที่มี credential | บัญชีธนาคารที่มียอดเงิน |
Order | entry ในตาราง orders | ความตั้งใจจะซื้อสินค้า |
Product | แถวหนึ่งในตาราง products | SKU, รายการใน catalog หรือของจริงที่จับต้องได้ ตกลงอันไหน? |
Ubiquitous Language คือ เลือกมาคำเดียว นิยามให้ชัด แล้วใช้คำนั้นทุกที่ ทั้งตอนคุยกัน ในโค้ด ใน column ของ database ใน API response ใน ticket และใน email
# BAD: The word "User" means nothing specific
class User:
def process(self, item): # "process" what? who is "user"?
...
# GOOD: Ubiquitous Language makes intent clear
class Customer:
def place_order(self, cart: ShoppingCart) -> Order:
...
class Seller:
def list_product(self, product: Product) -> Listing:
...
วิธีสร้าง Ubiquitous Language
- จัด workshop Domain Storytelling หรือ Event Storming (รายละเอียดอยู่ด้านล่าง)
- เขียน glossary — หนึ่งคำมีนิยามเดียว และทั้งสองฝั่งเห็นตรงกัน
- ตอน code review คอยดูการใช้คำผิด — ชื่อ class ไหนไม่อยู่ใน glossary ให้ทักกลับไป
- อัปเดต glossary ทุกครั้งที่เข้าใจ domain มากขึ้น
ขั้นที่ 3: Bounded Context — ขีดเส้นแบ่งให้ชัด¶
ประเด็นสำคัญคือ คำเดียวกันมีความหมายต่างกันได้ในแต่ละส่วนของระบบ ไม่ผิดอะไร ขอแค่ขีดเส้นแบ่งไว้ให้ชัด
Bounded Context คือเส้นแบ่งเชิงความหมาย (semantic boundary) ภายในเส้นนี้ใช้ model ชุดเดียว และแต่ละคำมีความหมายเดียวที่ชัดเจน
นึกถึงประเทศกับภาษาก็ได้ สมัยก่อนคำว่า "Billion" ในภาษาอังกฤษแบบอเมริกันคือ 10⁹ แต่แบบอังกฤษคือ 10¹² คนในประเทศเดียวกันไม่มีใครสับสน เพราะพรมแดนประเทศบอกอยู่แล้วว่าใช้ความหมายไหน
┌─────────────────────────────┐ ┌─────────────────────────────┐
│ SALES BOUNDED CONTEXT │ │ SHIPPING BOUNDED CONTEXT │
│ │ │ │
│ Customer = person who │ │ Customer = delivery │
│ buys things │ │ address + name │
│ │ │ │
│ Order = intent to purchase │ │ Order = package to deliver │
│ │ │ │
│ Product = what we sell │ │ Product = physical item │
│ (price, desc) │ │ (weight, dims) │
└─────────────────────────────┘ └─────────────────────────────┘
คำเดียวกัน ความหมายต่างกัน แต่มีเส้นแบ่งชัดเจน ตั้งใจออกแบบให้เป็นแบบนี้ ไม่ใช่ความผิดพลาด
หา Bounded Context ยังไง¶
ดูสัญญาณพวกนี้ในธุรกิจของคุณ:
- ต่างทีมใช้คำเดียวกันแต่หมายถึงคนละอย่าง (สัญญาณจากภาษา)
- ข้อมูลชุดเดียวกัน แต่ละแผนกตีความไม่เหมือนกัน (สัญญาณจากความหมาย)
- ส่วนของระบบที่แทบไม่เคยต้องแก้พร้อมกัน (สัญญาณจาก coupling)
- เส้นแบ่งในองค์กร — Conway's Law บอกว่าระบบจะออกมาหน้าตาเหมือนโครงสร้างองค์กร
Conway's Law
"Organizations which design systems are constrained to produce designs which are copies of the communication structures of these organizations." — Mel Conway, 1968
สรุปคือ ถ้าบริษัทมีทีม Sales กับทีม Shipping ที่แทบไม่คุยกัน ซอฟต์แวร์ก็ควรมี Sales bounded context กับ Shipping bounded context แยกกัน ถ้าฝืน Conway's Law ก็เตรียมทะเลาะกับ architecture ของตัวเองไปตลอด
Bounded Context ของจริง: ตัวอย่าง E-Commerce¶
ทั้งคู่มือนี้จะใช้แพลตฟอร์ม e-commerce เป็นตัวอย่าง บริษัท e-commerce ทั่วไปน่าจะมี bounded context หกตัวแบบนี้:
┌─────────────┐ ┌─────────────┐ ┌─────────────┐
│ CATALOG │ │ ORDERS │ │ PAYMENTS │
│ │ │ │ │ │
│ Products │ │ Orders │ │ Transactions│
│ Categories │ │ Line Items │ │ Refunds │
│ Search │ │ Discounts │ │ Invoices │
└─────────────┘ └─────────────┘ └─────────────┘
┌─────────────┐ ┌─────────────┐ ┌─────────────┐
│ SHIPPING │ │ CUSTOMERS │ │ NOTIFICATIONS│
│ │ │ │ │ │
│ Shipments │ │ Profiles │ │ Emails │
│ Tracking │ │ Addresses │ │ SMS │
│ Carriers │ │ Preferences │ │ Push Alerts │
└─────────────┘ └─────────────┘ └─────────────┘
หนึ่งกล่องคือหนึ่ง bounded context แต่ละกล่องมี model ของตัวเอง และ (ถ้าทำได้) ไม่ใช้ตาราง database ร่วมกับกล่องอื่นเลย
ขั้นที่ 4: Context Map — Bounded Context คุยกันยังไง¶
Context Map คือเอกสารที่บอกว่า bounded context แต่ละตัวเกี่ยวข้องกันยังไง ไม่ได้มีแค่เรื่องเทคนิค แต่สะท้อนการเมืองและพลวัตในองค์กรด้วย
context mapping pattern คลาสสิกมีเก้าแบบ ถ้าเข้าใจครบ คุณจะเลือกวิธี integrate อย่างตั้งใจ ไม่ใช่ต่อสายเข้าหากันไปเรื่อย
Upstream vs Downstream¶
ก่อนดู pattern ต้องเข้าใจเรื่องทิศทางก่อน:
- Upstream (U) — ฝั่งที่ให้ ถ้าตรงนี้เปลี่ยน downstream ก็โดนผลกระทบตามไปด้วย
- Downstream (D) — ฝั่งที่ใช้ ต้องปรับตามสิ่งที่ upstream ส่งมาให้
[Orders] ──────────────────→ [Payments]
Upstream (U) Downstream (D)
Orders creates payment requests. Payments must adapt to Orders' model.
Context Mapping Pattern ทั้งเก้าแบบ¶
สองทีมรอดหรือร่วงไปด้วยกัน ประสานงานกันและปรับ interface ไปพร้อมกัน ไม่มีใครเป็น upstream หรือ downstream ร่วมมือกันล้วน ๆ
ใช้เมื่อ: สองทีม coupled กันแน่นและ release ในจังหวะเดียวกัน
model ที่สองทีมเป็นเจ้าของร่วมกัน จะแก้โค้ดส่วนที่แชร์ ต้องให้ทั้งสองทีมตกลงกันก่อน
ใช้เมื่อ: สอง context มี concept ที่เหมือนกันจริง ๆ และรับต้นทุนการประสานงานไหว
# Shared kernel: a library both contexts import
# shared_kernel/money.py
@dataclass(frozen=True)
class Money:
amount: Decimal
currency: str
def add(self, other: 'Money') -> 'Money':
if self.currency != other.currency:
raise ValueError("Cannot add different currencies")
return Money(self.amount + other.amount, self.currency)
Warning
Shared Kernel ทำให้เกิด coupling ใช้เท่าที่จำเป็น และทำ model ที่แชร์ให้เล็กที่สุด
ทีมหนึ่งเป็น customer (downstream) อีกทีมเป็น supplier (upstream) customer ขอ feature ได้ แต่ supplier เป็นคนตัดสินว่าจะทำหรือไม่ อำนาจไม่เท่ากันชัดเจน แต่ต่างฝ่ายก็มีความรับผิดชอบที่ชัดเจนเหมือนกัน
ใช้เมื่อ: ทีมหนึ่งให้บริการอีกทีม และอยากมีช่องทางคุยกันอย่างเป็นทางการ
downstream ใช้ model ของ upstream ตามนั้นเลย ไม่แปลอะไร downstream ยอมเสียความเป็นอิสระ มักเกิดตอนที่ upstream ไม่ยอมต่อรองหรือปรับให้
ใช้เมื่อ: integrate กับ third-party provider รายใหญ่ (อย่าง AWS หรือ Salesforce) ที่คุณไปเปลี่ยน model ของเขาไม่ได้อยู่แล้ว
downstream แปล model ของ upstream ให้เป็น model ของตัวเอง ACL กันไม่ให้ concept จากข้างนอกซึมเข้ามาปน domain ของคุณ เป็น pattern สายป้องกัน
ใช้เมื่อ: integrate กับระบบ legacy, external API หรือ upstream ที่ model เละ หรือไปด้วยกันกับของคุณไม่ได้
# Upstream: Legacy CRM with a terrible model
class LegacyCRMCustomer:
cust_no: str # this is actually our customer ID
f_name: str
l_name: str
addr1: str # actually a full address serialized as string
acct_bal: float # this is credit limit, not balance
# Anti-Corruption Layer: translates legacy → our model
class CustomerACL:
def __init__(self, crm_client):
self._crm = crm_client
def get_customer(self, customer_id: str) -> Customer:
raw = self._crm.fetch(customer_id)
return Customer(
id=CustomerId(raw.cust_no),
name=PersonName(first=raw.f_name, last=raw.l_name),
address=Address.parse(raw.addr1),
credit_limit=Money(Decimal(str(raw.acct_bal)), "USD")
)
upstream เปิด protocol ที่นิยามชัดและนิ่งให้ consumer ทุกตัวใช้ เหมือน public API ที่มี versioning และเอกสาร downstream context หลายตัวต่อเข้ามาได้เลย ไม่ต้องทำ integration เฉพาะให้ทีละตัว
ใช้เมื่อ: context ของคุณมี context อื่นมาใช้บริการเยอะ และต้องการจุด integrate ที่นิ่ง
ภาษากลาง (schema) ที่มีเอกสารชัดเจน ใช้คุยกันระหว่าง context มักใช้คู่กับ Open Host Service เช่น JSON Schema, Protobuf, AsyncAPI spec
สอง context ไม่ integrate กันเลย ต่างฝ่ายต่างแก้ปัญหาที่คล้ายกันเอง ฟังดูเปลือง แต่บางครั้งก็คุ้มกว่า ถ้าต้นทุนการ integrate สูงกว่าต้นทุนของการทำซ้ำ
ใช้เมื่อ: integrate แล้วต้องคุยกันวุ่นวายจนแพงกว่าดูแลสอง solution แยกกัน
สภาพจริงของระบบเก่าจำนวนมาก — ไม่มีเส้นแบ่งชัด ทุกอย่างคุยกับทุกอย่าง แทบไม่มี model อะไรเลย DDD นับเรื่องนี้เป็น pattern หนึ่งที่คุณอาจต้องหาทาง อ้อม (ด้วย ACL) ระหว่างที่ค่อย ๆ เก็บกวาด
ภาค 2: Tactical Design¶
ทีนี้ลงโค้ดกันแล้ว Tactical design คือชุด building block สำหรับ model domain ของคุณ pattern ทั้งหมดนี้อยู่ ข้างใน bounded context
Building Block ต่าง ๆ¶
Inside a Bounded Context:
┌────────────────────────────────────────────────────────────┐
│ APPLICATION LAYER │
│ (orchestrates, coordinates, no logic) │
├────────────────────────────────────────────────────────────┤
│ DOMAIN LAYER │
│ ┌──────────┐ ┌─────────────┐ ┌──────────────────────┐ │
│ │Aggregates│ │ Entities │ │ Value Objects │ │
│ └──────────┘ └─────────────┘ └──────────────────────┘ │
│ ┌──────────┐ ┌─────────────┐ ┌──────────────────────┐ │
│ │ Services │ │ Factories │ │ Domain Events │ │
│ └──────────┘ └─────────────┘ └──────────────────────┘ │
├────────────────────────────────────────────────────────────┤
│ INFRASTRUCTURE LAYER │
│ ┌──────────────────────────────────────────────────────┐ │
│ │ Repositories (talk to databases) │ │
│ └──────────────────────────────────────────────────────┘ │
└────────────────────────────────────────────────────────────┘
Entity — Identity ที่ไม่เปลี่ยน¶
Entity คือ object ที่ระบุตัวตนด้วย identity ไม่ใช่ด้วย attribute ต่อให้ attribute เปลี่ยนหมดทุกตัว ก็ยังเป็น entity ตัวเดิม
คนคนหนึ่งก็เป็น Entity ต่อให้เปลี่ยนชื่อ เปลี่ยนสีผม ย้ายบ้าน ก็ยังเป็นคนเดิม เพราะ identity ไม่ได้เปลี่ยนตาม
from dataclasses import dataclass, field
from uuid import UUID, uuid4
@dataclass
class Customer:
id: UUID # ← identity is what matters
name: str
email: str
loyalty_points: int = 0
def earn_points(self, points: int) -> None:
if points <= 0:
raise ValueError("Points must be positive")
self.loyalty_points += points
def __eq__(self, other):
if not isinstance(other, Customer):
return False
return self.id == other.id # equality based on ID only
def __hash__(self):
return hash(self.id)
ลักษณะสำคัญของ Entity
- มี unique identifier (UUID, sequential ID ฯลฯ)
- Mutable — state เปลี่ยนได้ตามเวลา
- entity สองตัวที่ ID เดียวกันคือตัวเดียวกัน attribute อื่นจะต่างกันยังไงก็ตาม
- เทียบ equality ด้วย identity ไม่ใช่ค่าของ attribute
Value Object — ไม่มี Identity, Immutable และใช้บรรยายค่า¶
Value Object คือ object ที่นิยามด้วย attribute ล้วน ๆ ไม่มี identity ถ้า value object สองตัวมี attribute เหมือนกัน ก็ใช้แทนกันได้เลย
ตัวอย่างคลาสสิกคือ Money $10.00 USD ก้อนไหนก็ใช้แทน $10.00 USD ก้อนอื่นได้ ไม่มีใครมานั่งจำว่าถือแบงก์ดอลลาร์ใบไหนอยู่
from dataclasses import dataclass
from decimal import Decimal
@dataclass(frozen=True) # frozen=True makes it immutable
class Money:
amount: Decimal
currency: str
def __post_init__(self):
if self.amount < 0:
raise ValueError("Money amount cannot be negative")
if len(self.currency) != 3:
raise ValueError("Currency must be a 3-letter ISO code")
def add(self, other: 'Money') -> 'Money':
if self.currency != other.currency:
raise ValueError(f"Cannot add {self.currency} and {other.currency}")
return Money(self.amount + other.amount, self.currency)
def multiply(self, factor: Decimal) -> 'Money':
return Money(self.amount * factor, self.currency)
def __str__(self):
return f"{self.amount} {self.currency}"
@dataclass(frozen=True)
class Address:
street: str
city: str
postal_code: str
country_code: str
def is_domestic(self, home_country: str) -> bool:
return self.country_code == home_country
Value Object หรือ Entity เลือกยังไง
ถามตัวเองว่า "เราสนใจว่าเป็น instance ตัวไหน หรือสนใจแค่ว่าแทนค่าอะไร?"
- Address บนซองจดหมาย: Value Object — ที่อยู่ไหนที่ street/city/zip ตรงกันก็ใช้แทนกันได้
- record ที่อยู่ของลูกค้า ใน CRM ที่เก็บประวัติที่อยู่: Entity — เพราะคุณสนใจว่าเป็น record ตัวนี้ ที่แก้ไปเมื่อวันนั้น
ในงานจริงคนใช้ Value Object น้อยเกินไป ถ้าลังเล ให้เลือก Value Object ไว้ก่อน ง่ายกว่า ปลอดภัยกว่า (immutable) และเทสต์ง่ายกว่า
Aggregate — เส้นแบ่งของ Consistency¶
นี่คือ tactical pattern ที่ทรงพลังที่สุด และคนเข้าใจผิดกันมากที่สุด
Aggregate คือกลุ่มของ Entity กับ Value Object ที่เรามองเป็นก้อนเดียวเวลา แก้ข้อมูล ทุก aggregate มี Entity ตัวหลักหนึ่งตัว เรียกว่า Aggregate Root
กฎมีสามข้อ: 1. ทุกการแก้ไขต้องผ่าน Aggregate Root object ข้างนอกห้ามแก้ entity ข้างในตรง ๆ 2. aggregate เป็นตัวคุม business invariant ทั้งหมด (กฎที่ต้องจริงอยู่เสมอ) 3. หนึ่ง transaction แก้ได้ ไม่เกินหนึ่ง aggregate
ลอง model aggregate Order กัน:
from dataclasses import dataclass, field
from uuid import UUID, uuid4
from decimal import Decimal
from enum import Enum
from typing import List
class OrderStatus(Enum):
DRAFT = "draft"
CONFIRMED = "confirmed"
SHIPPED = "shipped"
DELIVERED = "delivered"
CANCELLED = "cancelled"
@dataclass(frozen=True)
class ProductId:
value: UUID
@dataclass(frozen=True)
class OrderLineItem: # Value Object inside the aggregate
product_id: ProductId
product_name: str
unit_price: Money
quantity: int
def __post_init__(self):
if self.quantity <= 0:
raise ValueError("Quantity must be positive")
@property
def subtotal(self) -> Money:
return self.unit_price.multiply(Decimal(self.quantity))
@dataclass
class Order: # Aggregate Root — this is the entry point for all changes
id: UUID
customer_id: UUID
status: OrderStatus
_line_items: List[OrderLineItem] = field(default_factory=list)
_events: List[object] = field(default_factory=list) # domain events
@classmethod
def create(cls, customer_id: UUID) -> 'Order':
order = cls(
id=uuid4(),
customer_id=customer_id,
status=OrderStatus.DRAFT,
)
order._events.append(OrderCreated(order_id=order.id, customer_id=customer_id))
return order
def add_item(self, product_id: ProductId, name: str, price: Money, qty: int) -> None:
# Business rule: can only modify draft orders
if self.status != OrderStatus.DRAFT:
raise ValueError(f"Cannot add items to an order in {self.status} status")
# Business rule: max 50 items per order
if len(self._line_items) >= 50:
raise ValueError("Cannot add more than 50 line items to an order")
line_item = OrderLineItem(
product_id=product_id,
product_name=name,
unit_price=price,
quantity=qty
)
self._line_items.append(line_item)
def confirm(self) -> None:
# Business rule: cannot confirm an empty order
if not self._line_items:
raise ValueError("Cannot confirm an order with no items")
if self.status != OrderStatus.DRAFT:
raise ValueError(f"Cannot confirm an order in {self.status} status")
self.status = OrderStatus.CONFIRMED
self._events.append(OrderConfirmed(order_id=self.id, total=self.total))
def cancel(self, reason: str) -> None:
if self.status in (OrderStatus.SHIPPED, OrderStatus.DELIVERED):
raise ValueError("Cannot cancel an order that has already shipped")
self.status = OrderStatus.CANCELLED
self._events.append(OrderCancelled(order_id=self.id, reason=reason))
@property
def total(self) -> Money:
if not self._line_items:
return Money(Decimal("0"), "USD")
totals = [item.subtotal for item in self._line_items]
result = totals[0]
for t in totals[1:]:
result = result.add(t)
return result
def pull_events(self) -> List[object]:
events = list(self._events)
self._events.clear()
return events
พลาดเรื่อง Aggregate แบบที่เจอบ่อยที่สุด
ทำ aggregate ใหญ่เกินไป ถ้า aggregate Order ยัด Customer, Products, Inventory และ Payments ไว้ข้างใน เท่ากับคุณสร้างคอขวดเรื่อง lock ขนาดยักษ์ transaction ที่แตะตัวใดตัวหนึ่งจะ block ตัวอื่นทั้งหมด
หลักง่าย ๆ: ทำ aggregate ให้เล็กไว้ ถ้าไม่แน่ใจ ให้แยกออกจากกัน แล้วให้คุยกันผ่าน domain event
aggregate ควรใหญ่แค่ไหน¶
ถามว่า "object ชุดที่เล็กที่สุดที่ต้อง consistent ไปด้วยกันมีอะไรบ้าง?"
ยกตัวอย่าง order ใน e-commerce ถ้าแก้จำนวนของ line item ตัวเดียว ทั้ง order ต้องยัง consistent อยู่ (ต้องคำนวณยอดรวมใหม่ และเช็กกฎจำนวนรายการสูงสุด) เพราะฉะนั้น Order + LineItems คือเส้นแบ่ง aggregate ที่เหมาะ
คุณ ไม่ ต้องเอา Customer มาไว้ใน aggregate Order เพื่อคุมกฎของ order แค่อ้างถึง customerId ก็พอแล้ว
Domain Event — สิ่งที่เกิดขึ้นไปแล้ว¶
Domain Event คือเหตุการณ์สำคัญที่เกิดขึ้นใน domain ตั้งชื่อเป็น past tense เสมอ: NounPastTense
OrderConfirmedPaymentProcessedCustomerRegisteredShipmentDispatched
Domain event ช่วย decouple ได้ดีมาก ถ้า bounded context หนึ่งต้อง react กับสิ่งที่เกิดในอีก context ให้คุยกันผ่าน event แทนการเรียกกันตรง ๆ
from dataclasses import dataclass
from datetime import datetime, UTC
from uuid import UUID
@dataclass(frozen=True)
class DomainEvent:
occurred_at: datetime = field(default_factory=lambda: datetime.now(UTC))
@dataclass(frozen=True)
class OrderConfirmed(DomainEvent):
order_id: UUID
customer_id: UUID
total: Money
@dataclass(frozen=True)
class OrderCancelled(DomainEvent):
order_id: UUID
customer_id: UUID
reason: str
# Another bounded context listens:
class NotificationService:
def on_order_confirmed(self, event: OrderConfirmed) -> None:
# Send confirmation email
self._email_client.send_confirmation(
customer_id=event.customer_id,
order_id=event.order_id,
amount=str(event.total)
)
def on_order_cancelled(self, event: OrderCancelled) -> None:
# Send cancellation notification
self._email_client.send_cancellation(
customer_id=event.customer_id,
reason=event.reason
)
ชื่อ event สำคัญกว่าที่คิด
- ใช้ past tense — เป็นสิ่งที่เกิดไปแล้ว ไม่ใช่คำสั่ง
- เจาะจงให้ชัด —
OrderConfirmedไม่ใช่OrderUpdated - ใส่ข้อมูลให้พอที่ฝั่งรับจะ react ได้เลยโดยไม่ต้อง query เพิ่ม — event ควรจบในตัว
- อย่าใช้ event ภายใน aggregate เดียว — แบบนั้นก็แค่ method call ที่แต่งตัวมาใหม่
Repository — ชั้นที่ซ่อนเรื่อง Persistence¶
Repository เปิด interface หน้าตาแบบ collection ไว้ให้เข้าถึง aggregate และซ่อนรายละเอียดว่าเก็บและดึง aggregate ยังไง โค้ด domain ไม่ควรรู้เลยว่าข้อมูลอยู่ใน PostgreSQL, MongoDB หรือแค่ dict ใน memory
from abc import ABC, abstractmethod
from uuid import UUID
from typing import Optional
# Define the interface in the domain layer
class OrderRepository(ABC):
@abstractmethod
def save(self, order: Order) -> None:
...
@abstractmethod
def find_by_id(self, order_id: UUID) -> Optional[Order]:
...
@abstractmethod
def find_by_customer(self, customer_id: UUID) -> list[Order]:
...
# Implement in the infrastructure layer
class PostgresOrderRepository(OrderRepository):
def __init__(self, db_session):
self._session = db_session
def save(self, order: Order) -> None:
record = self._to_record(order)
self._session.merge(record)
self._session.flush()
# Publish domain events after saving
for event in order.pull_events():
self._event_bus.publish(event)
def find_by_id(self, order_id: UUID) -> Optional[Order]:
record = self._session.query(OrderRecord).filter_by(id=order_id).first()
if not record:
return None
return self._to_domain(record)
def _to_record(self, order: Order) -> 'OrderRecord':
# Map domain object → database record
...
def _to_domain(self, record: 'OrderRecord') -> Order:
# Map database record → domain object
...
# In tests: swap for an in-memory implementation
class InMemoryOrderRepository(OrderRepository):
def __init__(self):
self._store: dict[UUID, Order] = {}
def save(self, order: Order) -> None:
self._store[order.id] = order
def find_by_id(self, order_id: UUID) -> Optional[Order]:
return self._store.get(order_id)
def find_by_customer(self, customer_id: UUID) -> list[Order]:
return [o for o in self._store.values() if o.customer_id == customer_id]
กฎของ Repository
- หนึ่ง repository ต่อหนึ่ง aggregate root ไม่ใช่หนึ่งต่อ entity
- interface ของ repository อยู่ใน domain layer
- ตัว implementation อยู่ใน infrastructure layer
- ห้ามใส่ business logic ใน repository — มีไว้เข้าถึงข้อมูลอย่างเดียว
- เทสต์ domain logic ด้วย repository แบบ
InMemory— เร็ว และไม่ต้องมี database
Domain Service — Logic ที่ไม่ได้เป็นของ Entity ตัวไหน¶
business logic บางอย่างคร่อมหลาย aggregate โดยธรรมชาติ หรือจะยัดใส่ entity ตัวไหนก็ไม่ลงตัว แบบนี้แหละที่ต้องใช้ Domain Service
# This logic involves two aggregates: Inventory and Order
# It doesn't naturally belong to either one alone
class OrderFulfillmentService:
def __init__(
self,
order_repo: OrderRepository,
inventory_repo: InventoryRepository,
event_bus: EventBus
):
self._orders = order_repo
self._inventory = inventory_repo
self._event_bus = event_bus
def fulfill_order(self, order_id: UUID) -> None:
order = self._orders.find_by_id(order_id)
if not order:
raise OrderNotFoundError(order_id)
for item in order.line_items:
inventory = self._inventory.find_by_product(item.product_id)
if not inventory.can_fulfill(item.quantity):
raise InsufficientInventoryError(item.product_id)
# Reserve inventory for each item
for item in order.line_items:
inventory = self._inventory.find_by_product(item.product_id)
inventory.reserve(item.quantity)
self._inventory.save(inventory)
order.mark_as_processing()
self._orders.save(order)
Domain Service vs Application Service¶
ตรงนี้คนสับสนกันบ่อย:
| Domain Service | Application Service | |
|---|---|---|
| อยู่ใน | Domain layer | Application layer |
| มีอะไรข้างใน | Business logic | Orchestration logic |
| รู้จักอะไร | Domain concept | Use case |
| Dependency | Domain object ตัวอื่น | Repository, domain service, external service |
| เทสต์ได้โดยไม่ต้องมี | Infrastructure | Infrastructure |
# Application Service: orchestrates, doesn't contain business logic
class PlaceOrderUseCase:
def __init__(
self,
order_repo: OrderRepository,
customer_repo: CustomerRepository,
fulfillment_service: OrderFulfillmentService,
notification_service: NotificationService
):
self._orders = order_repo
self._customers = customer_repo
self._fulfillment = fulfillment_service
self._notifications = notification_service
def execute(self, command: PlaceOrderCommand) -> UUID:
# Validate customer exists
customer = self._customers.find_by_id(command.customer_id)
if not customer:
raise CustomerNotFoundError(command.customer_id)
# Create order (domain logic)
order = Order.create(customer_id=command.customer_id)
for item in command.items:
order.add_item(
product_id=item.product_id,
name=item.product_name,
price=item.price,
qty=item.quantity
)
order.confirm()
# Persist
self._orders.save(order)
# Coordinate side effects
self._fulfillment.fulfill_order(order.id)
return order.id
Factory — สร้าง Object ที่ซับซ้อน¶
ถ้าการสร้าง aggregate ซับซ้อน (validate หลายชั้น ต้องโหลดข้อมูลที่เกี่ยวข้อง ต้องตั้ง invariant ให้ครบ) ให้ใช้ Factory ห่อ logic การสร้างไว้ในที่เดียว
class OrderFactory:
def __init__(self, product_catalog: ProductCatalog):
self._catalog = product_catalog
def create_from_cart(self, customer_id: UUID, cart: ShoppingCart) -> Order:
if cart.is_empty():
raise ValueError("Cannot create an order from an empty cart")
order = Order.create(customer_id=customer_id)
for cart_item in cart.items:
# Enrich with current product data from catalog
product = self._catalog.find_by_id(cart_item.product_id)
if not product:
raise ProductNotFoundError(cart_item.product_id)
if not product.is_available():
raise ProductUnavailableError(cart_item.product_id)
order.add_item(
product_id=product.id,
name=product.name,
price=product.current_price, # use current price, not cached cart price
qty=cart_item.quantity
)
return order
ภาค 3: ลงมือทำ DDD จริงด้วย Event Storming¶
Event Storming เป็นเทคนิค workshop ที่ทุกคนช่วยกันทำ Alberto Brandolini เป็นคนคิดขึ้นมา และเป็นวิธีที่เร็วที่สุดในการหา domain event, command และ aggregate ถ้าจะเริ่ม DDD แบบลงมือจริง เริ่มตรงนี้
Event Storming ทำยังไง¶
ของที่ต้องเตรียม: ผนังยาว ๆ หนึ่งผืน, sticky note 6 สี และคนที่ต้องอยู่ให้ครบ (developer, business analyst, domain expert, ops)
| สี | แทนอะไร | ตัวอย่าง |
|---|---|---|
| 🟠 ส้ม | Domain Event (past tense) | Order Confirmed |
| 🔵 น้ำเงิน | Command (รูปคำสั่ง) | Confirm Order |
| 🟡 เหลือง | Aggregate (คำนาม) | Order |
| 🟣 ม่วง | Policy (เมื่อ X ให้ทำ Y) | When payment received → fulfill order |
| 🩷 ชมพู | External System | Stripe, FedEx API |
| 🟢 เขียว | Read Model / View | Order Summary Page |
ขั้นตอน (4 ชั่วโมง)¶
-
ระดมแบบไม่มีกติกา (45 นาที): ทุกคนเขียน domain event ลง sticky สีส้ม แล้วแปะบนผนังตรงไหนก็ได้ ไม่มีกฎ ไม่มีใครตัดสินใคร
-
Timeline (30 นาที): เรียง event ตามลำดับเวลา จะเห็นจุดที่ขัดกันและ event ที่ตกหล่น
-
Command และ Actor (30 นาที): แต่ละ event ให้เติม command สีน้ำเงินที่ทำให้เกิด event นั้น และระบุว่าใครหรืออะไรเป็นคนสั่ง
-
Aggregate (30 นาที): จับกลุ่ม command กับ event ที่เกี่ยวกันไว้ใต้ sticky สีเหลืองของ aggregate
-
Bounded Context (30 นาที): ขีดเส้นรอบกลุ่ม aggregate ที่ควรอยู่ด้วยกัน
-
Policy และ External System (45 นาที): เติม policy สีม่วง (กฎ automation) และ external system สีชมพู
สิ่งที่ได้คือภาพ domain ที่ทุกคนเห็นตรงกัน และใช้เป็นฐานของ architecture ต่อได้เลย
ผล Event Storming ของตัวอย่าง e-commerce
[Add to Cart] → CartItemAdded → [Checkout Initiated] → CheckoutStarted
↓
[Enter Payment] → PaymentSubmitted → [STRIPE] → PaymentProcessed
↓
→ OrderConfirmed → [Notify Customer] → ConfirmationEmailSent
↓
→ [Warehouse System] → InventoryReserved → ShipmentScheduled → OrderShipped
↓
→ TrackingCodeIssued → DeliveryConfirmed → OrderCompleted
DDD กับ Microservices — เข้าคู่กันพอดี¶
Bounded Context กับ microservice ไม่ใช่เรื่องเดียวกัน แต่จับคู่กันได้อย่างเป็นธรรมชาติ:
หนึ่ง Bounded Context → หนึ่ง Microservice (หรือหนึ่ง service หรือหนึ่ง module แล้วแต่ deployment model ของคุณ)
DDD จึงขาดไม่ได้สำหรับ microservices architecture ถ้าไม่มี bounded context microservice จะกลายเป็น distributed monolith คือได้ความซับซ้อนของระบบกระจายมาเต็ม ๆ แต่ไม่ได้ข้อดีเรื่องการแยกขาดจากกันเลย
┌──────────────────────────────────────────────────────────────┐
│ API GATEWAY │
└──────────────────────────────────────────────────────────────┘
│ │ │ │ │
▼ ▼ ▼ ▼ ▼
┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌───────────┐
│ Catalog │ │ Orders │ │Payments │ │Shipping │ │Customers │
│ Service │ │ Service │ │ Service │ │ Service │ │ Service │
└──────────┘ └──────────┘ └──────────┘ └──────────┘ └───────────┘
│ │ │ │ │
▼ ▼ ▼ ▼ ▼
┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌───────────┐
│ Catalog │ │ Orders │ │Payments │ │Shipping │ │Customers │
│ DB │ │ DB │ │ DB │ │ DB │ │ DB │
└──────────┘ └──────────┘ └──────────┘ └──────────┘ └───────────┘
│
┌───────────────┐
│ Event Bus │
│ (Kafka / │
│ RabbitMQ) │
└───────────────┘
กฎของ DDD Microservice¶
- แต่ละ service เป็นเจ้าของ database ของตัวเอง ไม่แชร์ และห้ามยิง SQL ข้าม service เด็ดขาด
- คุยกันผ่าน event ไม่เรียกกันตรง ๆ (เท่าที่ทำได้) service แต่ละตัวจะได้เป็นอิสระต่อกัน
- แต่ละ service เปิด API (REST, gRPC) ไว้ให้อ่านข้อมูลแบบ synchronous ส่วนการเปลี่ยน state แบบ async ใช้ event
- ขอบเขต service = ขอบเขต bounded context หนึ่งทีมดูแลหนึ่ง context และหนึ่ง context คือหนึ่ง service
Anti-Pattern ที่ควรเลี่ยง¶
Anemic Domain Model¶
anti-pattern ของ DDD ที่เจอบ่อยที่สุด domain object เป็นแค่กล่องเก็บข้อมูลที่มี getter กับ setter ส่วน logic ทั้งหมดไปกองอยู่ใน service class
# ANEMIC — this is just a data bag, not a domain model
@dataclass
class Order:
id: UUID
status: str
items: list
total: Decimal
# Logic lives elsewhere — hard to find, easy to duplicate
class OrderService:
def confirm_order(self, order: Order):
order.status = "confirmed" # no validation, no invariants enforced
def cancel_order(self, order: Order, reason: str):
order.status = "cancelled" # anyone can cancel any order, any time
def add_item(self, order: Order, item: dict):
order.items.append(item) # no limit, no validation
order.total += item['price'] * item['quantity']
# RICH DOMAIN MODEL — logic lives where it belongs
@dataclass
class Order:
id: UUID
status: OrderStatus
_items: list[OrderLineItem]
def confirm(self) -> None:
if not self._items:
raise EmptyOrderError()
if self.status != OrderStatus.DRAFT:
raise InvalidStateTransitionError(self.status, OrderStatus.CONFIRMED)
self.status = OrderStatus.CONFIRMED
def cancel(self, reason: str) -> None:
if self.status.is_terminal():
raise InvalidStateTransitionError(...)
self.status = OrderStatus.CANCELLED
God Aggregate¶
aggregate ที่ยัดทุกอย่างไว้ในตัวเดียว ถ้า aggregate User เก็บทั้งที่อยู่ วิธีชำระเงิน order preference และแต้มสะสม รอเจอปัญหา concurrency หนัก ๆ กับ object ก้อนมหึมาที่โหลดช้าได้เลย
แยกออกเป็นหลายตัว ทำ aggregate ให้เล็กและโฟกัสเรื่องเดียว
Domain Logic รั่วเข้า Application Layer¶
application layer มีหน้าที่ orchestrate ไม่ใช่ตัดสินใจ ถ้าเจอ business rule (ส่วนลด การเช็กสิทธิ์ validation) อยู่ใน use case class ให้ย้ายไปไว้ใน domain layer
ใช้ Domain Event ภายในมากเกินไป¶
Domain event มีไว้คุยข้าม aggregate และข้าม context ภายใน aggregate เดียวกันเรียก method ตรง ๆ ก็พอ อย่าสร้าง event CustomerNameChanged ให้ aggregate ตัวเดิม handle เองข้างใน แบบนั้นก็แค่ method call ที่ซับซ้อนเกินเหตุ
ใช้ DDD ตอนไหนดี¶
DDD ทรงพลังก็จริง แต่ต้องใช้เวลาเรียนรู้และลงทุนตั้งแต่แรก ไม่ใช่ทุกงานที่ควรใช้
ใช้ DDD เมื่อ:¶
- domain ซับซ้อนจริง ๆ — business rule, edge case และ workflow เยอะ
- domain นี้คือแกนของความได้เปรียบในการแข่งขัน
- มี (หรือหามาได้) domain expert ที่ยอมมาทำงานด้วยกัน
- ระบบต้องโตต่อไปอีกหลายปี ไม่ใช่แค่ไม่กี่เดือน
- มีหลายทีมที่ต้องทำงานกับระบบแบบแยกกันได้
ข้าม DDD (หรือใช้แบบเบา ๆ) เมื่อ:¶
- กำลังทำแอป CRUD ง่าย ๆ
- domain ไม่ซับซ้อน และทุกคนเข้าใจดีอยู่แล้ว
- เวลาบีบมาก และงานไม่ได้ซับซ้อน
- ทีมเล็ก และทุกคนมี mental model ตรงกันอยู่แล้ว
- เป็นโปรเจกต์อายุสั้นหรือแค่ prototype
เริ่มจาก Strategic Design อย่างเดียวก่อน
ไม่ต้องใช้ tactical pattern ครบทุกตัวตั้งแต่วันแรก เริ่มจากช่วยกันทำความเข้าใจ domain (Event Storming) วาง bounded context กับ ubiquitous language ให้ได้ก่อน แล้วค่อยเอา tactical pattern มาใช้ตรงที่ซับซ้อนพอจะคุ้ม
DDD Cheat Sheet ฉบับย่อ¶
Strategic Design¶
| Concept | นิยาม | สรุปบรรทัดเดียว |
|---|---|---|
| Domain | ขอบเขตเรื่องที่ทำ | ธุรกิจของคุณทำอะไร |
| Core Domain | ความได้เปรียบในการแข่งขัน | สร้างเองและลงทุนตรงนี้ |
| Supporting Domain | หนุน core แต่ใคร ๆ ก็มี | ทำให้ดีพอใช้ |
| Generic Domain | ของมาตรฐานทั่วไป | ซื้อหรือใช้ open source |
| Ubiquitous Language | คำศัพท์ร่วมกัน | หนึ่งคำ หนึ่งความหมาย |
| Bounded Context | เส้นแบ่งเชิงความหมาย | ขอบเขตที่ model หนึ่งใช้ได้ |
| Context Map | ความสัมพันธ์ระหว่าง context | ใครคุยกับใคร และคุยยังไง |
Context Mapping Pattern¶
| Pattern | ความสัมพันธ์ | ใช้เมื่อ |
|---|---|---|
| Partnership | ร่วมมือกันเท่าเทียม | ทีมที่ coupled กันแน่น |
| Shared Kernel | โค้ดร่วมกัน ตกลงร่วมกัน | model ที่แชร์มีขนาดเล็ก |
| Customer-Supplier | upstream/downstream แบบเป็นทางการ | ต่างทีม ต่างรอบ release |
| Conformist | downstream ทำตามทั้งหมด | upstream รายใหญ่ที่คุณไปเปลี่ยนอะไรไม่ได้ |
| Anti-Corruption Layer | downstream แปลให้ | upstream ที่เป็น legacy หรือเละ |
| Open Host Service | upstream เผยแพร่ API | integration แบบหนึ่งต่อหลาย |
| Published Language | schema/format ร่วมกัน | protocol มาตรฐานสำหรับ event/API |
| Separate Ways | ไม่มี integration | ต้นทุน integration > ประโยชน์ |
| Big Ball of Mud | ไม่มี model ชัดเจน | สภาพจริงของ legacy — หาทางอ้อม |
Building Block ของ Tactical Design¶
| Building Block | มี Identity? | Mutable? | จุดประสงค์ |
|---|---|---|---|
| Entity | มี (มี ID) | ใช่ | สิ่งที่มี lifecycle และ identity |
| Value Object | ไม่มี | ไม่ (immutable) | attribute เชิงบรรยาย |
| Aggregate | มี (root ID) | ใช่ | ขอบเขตของ consistency |
| Domain Event | N/A | ไม่ | สิ่งที่เกิดขึ้นแล้ว |
| Repository | N/A | N/A | abstraction ของ persistence |
| Domain Service | N/A | N/A | logic ที่คร่อมหลาย object |
| Factory | N/A | N/A | การสร้าง object ที่ซับซ้อน |
| Application Service | N/A | N/A | orchestrate use case |
อ่านเพิ่มเติม¶
DDD เป็นเรื่องที่ลึก แหล่งข้อมูลพวกนี้จะพาคุณจากคนที่ใช้เป็นไปถึงระดับผู้เชี่ยวชาญ:
| แหล่งข้อมูล | ประเภท | เหมาะกับ |
|---|---|---|
| Domain-Driven Design โดย Eric Evans | หนังสือ | ต้นฉบับ — อ่านยากแต่เป็นตำราหลัก |
| Implementing Domain-Driven Design โดย Vaughn Vernon | หนังสือ | เน้น implement จริง ตัวอย่างโค้ดดีกว่า |
| Learning Domain-Driven Design โดย Vlad Khononov | หนังสือ | ทันสมัยและอ่านง่าย — มือใหม่เริ่มเล่มนี้ |
| Domain Storytelling โดย Hofer & Schwentner | หนังสือ | เทคนิคค้นหา domain ร่วมกัน |
| ddd-crew/ddd-starter-modelling-process | GitHub | คู่มือกระบวนการทีละขั้น |
| EventStorming.com | Web | แหล่งข้อมูลหลักของ Alberto Brandolini |
สรุป¶
สุดท้ายแล้ว Domain-Driven Design มีเป้าหมายเดียว: ปิดช่องว่างระหว่างคนที่เข้าใจธุรกิจกับคนที่สร้างซอฟต์แวร์
ลำดับขั้นเป็นแบบนี้:
- ค้นหา domain ผ่าน workshop ที่ทุกคนช่วยกันทำ (Event Storming)
- แยกประเภท subdomain — ลงทุนกับ Core, Supporting และ Generic ให้เหมาะกับแต่ละแบบ
- วาง Ubiquitous Language — คำศัพท์ชุดเดียวกัน ไม่มีความกำกวม
- กำหนด Bounded Context — ขอบเขตที่ model ใช้ได้ และทีมทำงานได้อิสระ
- Map ความสัมพันธ์ระหว่าง Context — partnership, ACL, conformist, event
- Model domain ลงโค้ด — Entity ที่มี logic อยู่ในตัว, Value Object ที่ immutable, Aggregate ที่คุม invariant
- สื่อสาร ข้ามเส้นแบ่งผ่าน Domain Event
- วนปรับ ไปเรื่อย ๆ — DDD คือบทสนทนาที่ไม่มีวันจบ
โค้ดคือ model ของสิ่งที่คุณเข้าใจ ยิ่งเข้าใจ domain ลึกขึ้น model ก็ควรลึกตามไปด้วย นี่แหละแก่นของ Domain-Driven Design
มีคำถามหรือความคิดเห็น? ติดต่อผมได้ที่ LinkedIn หรือทาง email
มีคำถามหรืออยากคุยกันต่อ? ติดต่อได้ที่ LinkedIn, X หรือทาง email
Discussion
Have thoughts on this post? Share them below — questions, corrections, or your own experience are all welcome.