[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M70NG057252CJT7ZXZYN2ESN":3,"skill-same:01M70NG057252CJT7ZXZYN2ESN":78},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":28,"publishedAt":49,"linkOnly":50,"markdownContent":51,"markdownBody":52,"frontMatter":53,"refName":54,"commitSha":55,"skillDirectory":56,"forksCount":57,"repositoryHtmlUrl":58,"repositoryHomepageUrl":59,"ownerHtmlUrl":60,"ownerBlogUrl":61,"ownerDescription":62,"updatedAt":63,"install":64,"resources":77},"01M70NG057252CJT7ZXZYN2ESN","domain-driven-design",null,"Domain-Driven Design tactical and strategic patterns including entities, value objects, aggregates, bounded contexts, and consistency strategies. Use when modeling business domains, designing aggregate boundaries, implementing business rules, or planning data consistency.","shengdabai\u002FTony-Claude-Code-Skills","shengdabai","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F116417419?v=4","01M70F6D2WY5PQV5A92BKYJQEW","Tony Sheng","01M70F6D3GAAAYZ5H4CC1G8VXM",3,"MIT","https:\u002F\u002Fgithub.com\u002Fshengdabai\u002FTony-Claude-Code-Skills\u002Fblob\u002Fmain\u002Fskills\u002Frsmdt-the-startup\u002Fplugins\u002Fteam\u002Fskills\u002Fdevelopment\u002Fdomain-driven-design\u002FSKILL.md",[18,23],{"categoryNo":19,"categoryName":20,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000015","视觉设计","SCENARIO","使用场景",{"categoryNo":24,"categoryName":25,"taxonomyType":26,"taxonomyTypeDesc":27},"01JBSEEDCAT000000000000032","设计师","PROFESSION","适用职业",[29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48],"design","domain","driven","domain driven design","use","strategic","planning","value","consistency","bounded","patterns","data","modeling","strategies","when","objects","domains","implementing","aggregates","tactical","2026-11-10 10:12:30",false,"---\nname: domain-driven-design\ndescription: Domain-Driven Design tactical and strategic patterns including entities, value objects, aggregates, bounded contexts, and consistency strategies. Use when modeling business domains, designing aggregate boundaries, implementing business rules, or planning data consistency.\n---\n\n# Domain-Driven Design Patterns\n\nPatterns for modeling complex business domains with clear boundaries, enforced invariants, and appropriate consistency strategies.\n\n## When to Activate\n\n- Modeling business domains and entities\n- Designing aggregate boundaries\n- Implementing complex business rules\n- Planning data consistency strategies\n- Establishing bounded contexts\n- Designing domain events and integration\n\n## Strategic Patterns\n\n### Bounded Context\n\nA bounded context defines the boundary within which a domain model applies. The same term can mean different things in different contexts.\n\n```\nExample: \"Customer\" in different contexts\n\n┌─────────────────┐  ┌─────────────────┐  ┌─────────────────┐\n│    Sales        │  │    Support      │  │    Billing      │\n│    Context      │  │    Context      │  │    Context      │\n├─────────────────┤  ├─────────────────┤  ├─────────────────┤\n│ Customer:       │  │ Customer:       │  │ Customer:       │\n│ - Leads         │  │ - Tickets       │  │ - Invoices      │\n│ - Opportunities │  │ - SLA           │  │ - Payment       │\n│ - Proposals     │  │ - Satisfaction  │  │ - Credit Limit  │\n└─────────────────┘  └─────────────────┘  └─────────────────┘\n```\n\n#### Context Identification\n\nAsk these questions to find context boundaries:\n- Where does the ubiquitous language change?\n- Which teams own which concepts?\n- Where do integration points naturally occur?\n- What could be deployed independently?\n\n### Context Mapping\n\nDefine how bounded contexts integrate:\n\n| Pattern | Description | Use When |\n|---------|-------------|----------|\n| **Shared Kernel** | Shared code between contexts | Close collaboration, same team |\n| **Customer-Supplier** | Upstream\u002Fdownstream relationship | Clear dependency direction |\n| **Conformist** | Downstream adopts upstream model | No negotiation power |\n| **Anti-Corruption Layer** | Translation layer between models | Protecting domain from external models |\n| **Open Host Service** | Published API for integration | Multiple consumers |\n| **Published Language** | Shared interchange format | Industry standards exist |\n\n### Ubiquitous Language\n\nThe shared vocabulary between developers and domain experts:\n\n```\nBuilding Ubiquitous Language:\n\n1. EXTRACT terms from domain expert conversations\n2. DOCUMENT in a glossary with precise definitions\n3. ENFORCE in code - class names, method names, variables\n4. EVOLVE as understanding deepens\n\nExample Glossary Entry:\n┌─────────────────────────────────────────────────────────────┐\n│ Term: Order                                                  │\n│ Definition: A confirmed request from a customer to purchase │\n│             one or more products at agreed prices.          │\n│ NOT: A shopping cart (which is an Intent, not an Order)     │\n│ Context: Sales                                              │\n└─────────────────────────────────────────────────────────────┘\n```\n\n## Tactical Patterns\n\n### Entities\n\nObjects with identity that persists over time. Equality is based on identity, not attributes.\n\n```\nCharacteristics:\n- Has a unique identifier\n- Mutable state\n- Lifecycle (created, modified, archived)\n- Equality by ID\n\nExample:\n┌─────────────────────────────────────────┐\n│ Entity: Order                           │\n├─────────────────────────────────────────┤\n│ Identity: orderId (UUID)                │\n│ State: status, items, total             │\n│ Behavior: addItem(), submit(), cancel() │\n└─────────────────────────────────────────┘\n\nclass Order {\n  private readonly id: OrderId;      \u002F\u002F Identity - immutable\n  private status: OrderStatus;        \u002F\u002F State - mutable\n  private items: OrderItem[];         \u002F\u002F State - mutable\n\n  constructor(id: OrderId) {\n    this.id = id;\n    this.status = OrderStatus.Draft;\n    this.items = [];\n  }\n\n  equals(other: Order): boolean {\n    return this.id.equals(other.id);  \u002F\u002F Equality by identity\n  }\n}\n```\n\n### Value Objects\n\nObjects without identity. Equality is based on attributes. Always immutable.\n\n```\nCharacteristics:\n- No unique identifier\n- Immutable (all properties readonly)\n- Equality by attributes\n- Self-validating\n\nExample:\n┌─────────────────────────────────────────┐\n│ Value Object: Money                     │\n├─────────────────────────────────────────┤\n│ Attributes: amount, currency            │\n│ Behavior: add(), subtract(), format()   │\n│ Invariant: amount >= 0                  │\n└─────────────────────────────────────────┘\n\nclass Money {\n  constructor(\n    public readonly amount: number,\n    public readonly currency: Currency\n  ) {\n    if (amount \u003C 0) throw new Error('Amount cannot be negative');\n  }\n\n  add(other: Money): Money {\n    if (!this.currency.equals(other.currency)) {\n      throw new Error('Cannot add different currencies');\n    }\n    return new Money(this.amount + other.amount, this.currency);\n  }\n\n  equals(other: Money): boolean {\n    return this.amount === other.amount &&\n           this.currency.equals(other.currency);\n  }\n}\n```\n\n#### When to Use Value Objects\n\n| Use Value Object | Use Entity |\n|------------------|------------|\n| No need to track over time | Need to track lifecycle |\n| Interchangeable instances | Unique identity matters |\n| Defined by attributes | Defined by continuity |\n| Examples: Money, Address, DateRange | Examples: User, Order, Account |\n\n### Aggregates\n\nA cluster of entities and value objects with a defined boundary. One entity is the aggregate root.\n\n```\nAggregate Design Rules:\n\n1. PROTECT invariants at aggregate boundary\n2. REFERENCE other aggregates by identity only\n3. UPDATE one aggregate per transaction\n4. DESIGN small aggregates (prefer single entity)\n\nExample:\n┌─────────────────────────────────────────────────────────────┐\n│ Aggregate: Order                                            │\n│ Root: Order (entity)                                        │\n├─────────────────────────────────────────────────────────────┤\n│  ┌─────────────────┐                                        │\n│  │ Order (Root)    │◄── Aggregate Root                      │\n│  │ - orderId       │                                        │\n│  │ - customerId ───┼──► Reference by ID only                │\n│  │ - status        │                                        │\n│  └────────┬────────┘                                        │\n│           │                                                 │\n│  ┌────────▼────────┐                                        │\n│  │ OrderItem       │◄── Inside aggregate                    │\n│  │ - productId ────┼──► Reference by ID only                │\n│  │ - quantity      │                                        │\n│  │ - price (Money) │◄── Value Object                        │\n│  └─────────────────┘                                        │\n└─────────────────────────────────────────────────────────────┘\n```\n\n#### Aggregate Sizing\n\n```\nStart Small:\n- Begin with single-entity aggregates\n- Expand only when invariants require it\n\nSigns of Too-Large Aggregate:\n- Frequent optimistic lock conflicts\n- Loading too much data for simple operations\n- Multiple users editing simultaneously\n- Transactional failures across unrelated data\n\nSigns of Too-Small Aggregate:\n- Invariants not protected\n- Business rules scattered across services\n- Eventual consistency where immediate is required\n```\n\n### Domain Events\n\nRepresent something that happened in the domain. Immutable facts about the past.\n\n```\nEvent Structure:\n┌─────────────────────────────────────────┐\n│ Event: OrderPlaced                      │\n├─────────────────────────────────────────┤\n│ eventId: UUID                           │\n│ occurredAt: DateTime                    │\n│ aggregateId: orderId                    │\n│ payload:                                │\n│   - customerId                          │\n│   - items                               │\n│   - totalAmount                         │\n└─────────────────────────────────────────┘\n\nNaming Convention:\n- Past tense (OrderPlaced, not PlaceOrder)\n- Domain language (not technical)\n- Include all relevant data (event is immutable)\n\nclass OrderPlaced implements DomainEvent {\n  readonly eventId = uuid();\n  readonly occurredAt = new Date();\n\n  constructor(\n    readonly orderId: OrderId,\n    readonly customerId: CustomerId,\n    readonly items: OrderItemData[],\n    readonly totalAmount: Money\n  ) {}\n}\n```\n\n#### Event Patterns\n\n| Pattern | Description | Use Case |\n|---------|-------------|----------|\n| **Event Notification** | Minimal data, query for details | Loose coupling |\n| **Event-Carried State** | Full data in event | Performance, offline |\n| **Event Sourcing** | Events as source of truth | Audit, temporal queries |\n\n### Repositories\n\nAbstract persistence, providing collection-like access to aggregates.\n\n```\nRepository Principles:\n- One repository per aggregate\n- Returns aggregate roots only\n- Hides persistence mechanism\n- Supports aggregate reconstitution\n\ninterface OrderRepository {\n  findById(id: OrderId): Promise\u003COrder | null>;\n  findByCustomer(customerId: CustomerId): Promise\u003COrder[]>;\n  save(order: Order): Promise\u003Cvoid>;\n  delete(order: Order): Promise\u003Cvoid>;\n}\n\n\u002F\u002F Implementation hides persistence details\nclass PostgresOrderRepository implements OrderRepository {\n  async findById(id: OrderId): Promise\u003COrder | null> {\n    const row = await this.db.query('SELECT * FROM orders WHERE id = $1', [id]);\n    return row ? this.reconstitute(row) : null;\n  }\n\n  private reconstitute(row: OrderRow): Order {\n    \u002F\u002F Rebuild aggregate from persistence\n  }\n}\n```\n\n## Consistency Strategies\n\n### Transactional Consistency (ACID)\n\nUse for invariants within an aggregate:\n\n```\nRule: One aggregate per transaction\n\n\u002F\u002F Good: Single aggregate updated\nasync function addItemToOrder(orderId: OrderId, item: OrderItem) {\n  const order = await orderRepo.findById(orderId);\n  order.addItem(item);  \u002F\u002F Business rules enforced\n  await orderRepo.save(order);\n}\n\n\u002F\u002F Bad: Multiple aggregates in one transaction\nasync function createOrderWithInventory() {\n  await db.transaction(async (tx) => {\n    await orderRepo.save(order, tx);\n    await inventoryRepo.decrement(productId, quantity, tx);  \u002F\u002F Don't do this\n  });\n}\n```\n\n### Eventual Consistency\n\nUse for consistency across aggregates:\n\n```\nPattern: Domain Events + Handlers\n\n\u002F\u002F Order aggregate publishes event\nclass Order {\n  submit(): void {\n    this.status = OrderStatus.Placed;\n    this.addEvent(new OrderPlaced(this.id, this.customerId, this.items));\n  }\n}\n\n\u002F\u002F Separate handler updates inventory (eventually)\nclass InventoryHandler {\n  async handle(event: OrderPlaced): Promise\u003Cvoid> {\n    for (const item of event.items) {\n      await this.inventoryService.reserve(item.productId, item.quantity);\n    }\n  }\n}\n```\n\n### Saga Pattern\n\nCoordinate multiple aggregates with compensation:\n\n```\nSaga: Order Fulfillment\n\n┌─────────┐     ┌─────────────┐     ┌─────────────┐     ┌─────────┐\n│ Create  │────►│ Reserve     │────►│ Charge      │────►│ Ship    │\n│ Order   │     │ Inventory   │     │ Payment     │     │ Order   │\n└────┬────┘     └──────┬──────┘     └──────┬──────┘     └─────────┘\n     │                 │                   │\n     │ Compensate:     │ Compensate:       │ Compensate:\n     │ Cancel Order    │ Release Inventory │ Refund Payment\n     ▼                 ▼                   ▼\n\nOn failure at any step, execute compensation in reverse order.\n```\n\n### Choosing Consistency\n\n| Scenario | Strategy |\n|----------|----------|\n| Within single aggregate | Transactional (ACID) |\n| Across aggregates, same service | Eventual (domain events) |\n| Across services | Saga with compensation |\n| Read model updates | Eventual (projection) |\n\n## Anti-Patterns\n\n### Anemic Domain Model\n\n```\n\u002F\u002F Anti-pattern: Logic outside domain objects\nclass Order {\n  id: string;\n  items: Item[];\n  status: string;\n}\n\nclass OrderService {\n  calculateTotal(order: Order): number { ... }\n  validate(order: Order): boolean { ... }\n  submit(order: Order): void { ... }\n}\n\n\u002F\u002F Better: Logic inside domain objects\nclass Order {\n  private items: OrderItem[];\n  private status: OrderStatus;\n\n  get total(): Money {\n    return this.items.reduce((sum, item) => sum.add(item.subtotal), Money.zero());\n  }\n\n  submit(): void {\n    this.validate();\n    this.status = OrderStatus.Submitted;\n  }\n}\n```\n\n### Large Aggregates\n\n```\n\u002F\u002F Anti-pattern: Everything in one aggregate\nclass Customer {\n  orders: Order[];           \u002F\u002F Could be thousands\n  addresses: Address[];\n  paymentMethods: PaymentMethod[];\n  preferences: Preferences;\n  activityLog: Activity[];   \u002F\u002F Could be millions\n}\n\n\u002F\u002F Better: Separate aggregates referenced by ID\nclass Customer {\n  id: CustomerId;\n  defaultAddressId: AddressId;\n  defaultPaymentMethodId: PaymentMethodId;\n}\n\nclass Order {\n  customerId: CustomerId;    \u002F\u002F Reference by ID\n}\n```\n\n### Primitive Obsession\n\n```\n\u002F\u002F Anti-pattern: Primitive types for domain concepts\nfunction createOrder(\n  customerId: string,\n  productId: string,\n  quantity: number,\n  price: number,\n  currency: string\n) { ... }\n\n\u002F\u002F Better: Value objects\nfunction createOrder(\n  customerId: CustomerId,\n  productId: ProductId,\n  quantity: Quantity,\n  price: Money\n) { ... }\n```\n\n## Implementation Checklist\n\n### Aggregate Design\n\n- [ ] Single entity can be aggregate root\n- [ ] Invariants are protected at boundary\n- [ ] Other aggregates referenced by ID only\n- [ ] Fits in memory comfortably\n- [ ] One transaction per aggregate\n\n### Entity Implementation\n\n- [ ] Has unique identifier\n- [ ] Equality based on ID\n- [ ] Encapsulates business rules\n- [ ] State changes through methods\n\n### Value Object Implementation\n\n- [ ] All properties immutable\n- [ ] Equality based on attributes\n- [ ] Self-validating\n- [ ] Operations return new instances\n\n### Repository Implementation\n\n- [ ] One per aggregate\n- [ ] Returns aggregate roots only\n- [ ] Hides persistence details\n- [ ] Supports queries needed by domain\n\n## References\n\n- [Pattern Implementation Examples](examples\u002Fddd-patterns.md) - Code examples in multiple languages\n- [Aggregate Design Guide](reference.md) - Detailed aggregate sizing heuristics\n","# Domain-Driven Design Patterns\n\nPatterns for modeling complex business domains with clear boundaries, enforced invariants, and appropriate consistency strategies.\n\n## When to Activate\n\n- Modeling business domains and entities\n- Designing aggregate boundaries\n- Implementing complex business rules\n- Planning data consistency strategies\n- Establishing bounded contexts\n- Designing domain events and integration\n\n## Strategic Patterns\n\n### Bounded Context\n\nA bounded context defines the boundary within which a domain model applies. The same term can mean different things in different contexts.\n\n```\nExample: \"Customer\" in different contexts\n\n┌─────────────────┐  ┌─────────────────┐  ┌─────────────────┐\n│    Sales        │  │    Support      │  │    Billing      │\n│    Context      │  │    Context      │  │    Context      │\n├─────────────────┤  ├─────────────────┤  ├─────────────────┤\n│ Customer:       │  │ Customer:       │  │ Customer:       │\n│ - Leads         │  │ - Tickets       │  │ - Invoices      │\n│ - Opportunities │  │ - SLA           │  │ - Payment       │\n│ - Proposals     │  │ - Satisfaction  │  │ - Credit Limit  │\n└─────────────────┘  └─────────────────┘  └─────────────────┘\n```\n\n#### Context Identification\n\nAsk these questions to find context boundaries:\n- Where does the ubiquitous language change?\n- Which teams own which concepts?\n- Where do integration points naturally occur?\n- What could be deployed independently?\n\n### Context Mapping\n\nDefine how bounded contexts integrate:\n\n| Pattern | Description | Use When |\n|---------|-------------|----------|\n| **Shared Kernel** | Shared code between contexts | Close collaboration, same team |\n| **Customer-Supplier** | Upstream\u002Fdownstream relationship | Clear dependency direction |\n| **Conformist** | Downstream adopts upstream model | No negotiation power |\n| **Anti-Corruption Layer** | Translation layer between models | Protecting domain from external models |\n| **Open Host Service** | Published API for integration | Multiple consumers |\n| **Published Language** | Shared interchange format | Industry standards exist |\n\n### Ubiquitous Language\n\nThe shared vocabulary between developers and domain experts:\n\n```\nBuilding Ubiquitous Language:\n\n1. EXTRACT terms from domain expert conversations\n2. DOCUMENT in a glossary with precise definitions\n3. ENFORCE in code - class names, method names, variables\n4. EVOLVE as understanding deepens\n\nExample Glossary Entry:\n┌─────────────────────────────────────────────────────────────┐\n│ Term: Order                                                  │\n│ Definition: A confirmed request from a customer to purchase │\n│             one or more products at agreed prices.          │\n│ NOT: A shopping cart (which is an Intent, not an Order)     │\n│ Context: Sales                                              │\n└─────────────────────────────────────────────────────────────┘\n```\n\n## Tactical Patterns\n\n### Entities\n\nObjects with identity that persists over time. Equality is based on identity, not attributes.\n\n```\nCharacteristics:\n- Has a unique identifier\n- Mutable state\n- Lifecycle (created, modified, archived)\n- Equality by ID\n\nExample:\n┌─────────────────────────────────────────┐\n│ Entity: Order                           │\n├─────────────────────────────────────────┤\n│ Identity: orderId (UUID)                │\n│ State: status, items, total             │\n│ Behavior: addItem(), submit(), cancel() │\n└─────────────────────────────────────────┘\n\nclass Order {\n  private readonly id: OrderId;      \u002F\u002F Identity - immutable\n  private status: OrderStatus;        \u002F\u002F State - mutable\n  private items: OrderItem[];         \u002F\u002F State - mutable\n\n  constructor(id: OrderId) {\n    this.id = id;\n    this.status = OrderStatus.Draft;\n    this.items = [];\n  }\n\n  equals(other: Order): boolean {\n    return this.id.equals(other.id);  \u002F\u002F Equality by identity\n  }\n}\n```\n\n### Value Objects\n\nObjects without identity. Equality is based on attributes. Always immutable.\n\n```\nCharacteristics:\n- No unique identifier\n- Immutable (all properties readonly)\n- Equality by attributes\n- Self-validating\n\nExample:\n┌─────────────────────────────────────────┐\n│ Value Object: Money                     │\n├─────────────────────────────────────────┤\n│ Attributes: amount, currency            │\n│ Behavior: add(), subtract(), format()   │\n│ Invariant: amount >= 0                  │\n└─────────────────────────────────────────┘\n\nclass Money {\n  constructor(\n    public readonly amount: number,\n    public readonly currency: Currency\n  ) {\n    if (amount \u003C 0) throw new Error('Amount cannot be negative');\n  }\n\n  add(other: Money): Money {\n    if (!this.currency.equals(other.currency)) {\n      throw new Error('Cannot add different currencies');\n    }\n    return new Money(this.amount + other.amount, this.currency);\n  }\n\n  equals(other: Money): boolean {\n    return this.amount === other.amount &&\n           this.currency.equals(other.currency);\n  }\n}\n```\n\n#### When to Use Value Objects\n\n| Use Value Object | Use Entity |\n|------------------|------------|\n| No need to track over time | Need to track lifecycle |\n| Interchangeable instances | Unique identity matters |\n| Defined by attributes | Defined by continuity |\n| Examples: Money, Address, DateRange | Examples: User, Order, Account |\n\n### Aggregates\n\nA cluster of entities and value objects with a defined boundary. One entity is the aggregate root.\n\n```\nAggregate Design Rules:\n\n1. PROTECT invariants at aggregate boundary\n2. REFERENCE other aggregates by identity only\n3. UPDATE one aggregate per transaction\n4. DESIGN small aggregates (prefer single entity)\n\nExample:\n┌─────────────────────────────────────────────────────────────┐\n│ Aggregate: Order                                            │\n│ Root: Order (entity)                                        │\n├─────────────────────────────────────────────────────────────┤\n│  ┌─────────────────┐                                        │\n│  │ Order (Root)    │◄── Aggregate Root                      │\n│  │ - orderId       │                                        │\n│  │ - customerId ───┼──► Reference by ID only                │\n│  │ - status        │                                        │\n│  └────────┬────────┘                                        │\n│           │                                                 │\n│  ┌────────▼────────┐                                        │\n│  │ OrderItem       │◄── Inside aggregate                    │\n│  │ - productId ────┼──► Reference by ID only                │\n│  │ - quantity      │                                        │\n│  │ - price (Money) │◄── Value Object                        │\n│  └─────────────────┘                                        │\n└─────────────────────────────────────────────────────────────┘\n```\n\n#### Aggregate Sizing\n\n```\nStart Small:\n- Begin with single-entity aggregates\n- Expand only when invariants require it\n\nSigns of Too-Large Aggregate:\n- Frequent optimistic lock conflicts\n- Loading too much data for simple operations\n- Multiple users editing simultaneously\n- Transactional failures across unrelated data\n\nSigns of Too-Small Aggregate:\n- Invariants not protected\n- Business rules scattered across services\n- Eventual consistency where immediate is required\n```\n\n### Domain Events\n\nRepresent something that happened in the domain. Immutable facts about the past.\n\n```\nEvent Structure:\n┌─────────────────────────────────────────┐\n│ Event: OrderPlaced                      │\n├─────────────────────────────────────────┤\n│ eventId: UUID                           │\n│ occurredAt: DateTime                    │\n│ aggregateId: orderId                    │\n│ payload:                                │\n│   - customerId                          │\n│   - items                               │\n│   - totalAmount                         │\n└─────────────────────────────────────────┘\n\nNaming Convention:\n- Past tense (OrderPlaced, not PlaceOrder)\n- Domain language (not technical)\n- Include all relevant data (event is immutable)\n\nclass OrderPlaced implements DomainEvent {\n  readonly eventId = uuid();\n  readonly occurredAt = new Date();\n\n  constructor(\n    readonly orderId: OrderId,\n    readonly customerId: CustomerId,\n    readonly items: OrderItemData[],\n    readonly totalAmount: Money\n  ) {}\n}\n```\n\n#### Event Patterns\n\n| Pattern | Description | Use Case |\n|---------|-------------|----------|\n| **Event Notification** | Minimal data, query for details | Loose coupling |\n| **Event-Carried State** | Full data in event | Performance, offline |\n| **Event Sourcing** | Events as source of truth | Audit, temporal queries |\n\n### Repositories\n\nAbstract persistence, providing collection-like access to aggregates.\n\n```\nRepository Principles:\n- One repository per aggregate\n- Returns aggregate roots only\n- Hides persistence mechanism\n- Supports aggregate reconstitution\n\ninterface OrderRepository {\n  findById(id: OrderId): Promise\u003COrder | null>;\n  findByCustomer(customerId: CustomerId): Promise\u003COrder[]>;\n  save(order: Order): Promise\u003Cvoid>;\n  delete(order: Order): Promise\u003Cvoid>;\n}\n\n\u002F\u002F Implementation hides persistence details\nclass PostgresOrderRepository implements OrderRepository {\n  async findById(id: OrderId): Promise\u003COrder | null> {\n    const row = await this.db.query('SELECT * FROM orders WHERE id = $1', [id]);\n    return row ? this.reconstitute(row) : null;\n  }\n\n  private reconstitute(row: OrderRow): Order {\n    \u002F\u002F Rebuild aggregate from persistence\n  }\n}\n```\n\n## Consistency Strategies\n\n### Transactional Consistency (ACID)\n\nUse for invariants within an aggregate:\n\n```\nRule: One aggregate per transaction\n\n\u002F\u002F Good: Single aggregate updated\nasync function addItemToOrder(orderId: OrderId, item: OrderItem) {\n  const order = await orderRepo.findById(orderId);\n  order.addItem(item);  \u002F\u002F Business rules enforced\n  await orderRepo.save(order);\n}\n\n\u002F\u002F Bad: Multiple aggregates in one transaction\nasync function createOrderWithInventory() {\n  await db.transaction(async (tx) => {\n    await orderRepo.save(order, tx);\n    await inventoryRepo.decrement(productId, quantity, tx);  \u002F\u002F Don't do this\n  });\n}\n```\n\n### Eventual Consistency\n\nUse for consistency across aggregates:\n\n```\nPattern: Domain Events + Handlers\n\n\u002F\u002F Order aggregate publishes event\nclass Order {\n  submit(): void {\n    this.status = OrderStatus.Placed;\n    this.addEvent(new OrderPlaced(this.id, this.customerId, this.items));\n  }\n}\n\n\u002F\u002F Separate handler updates inventory (eventually)\nclass InventoryHandler {\n  async handle(event: OrderPlaced): Promise\u003Cvoid> {\n    for (const item of event.items) {\n      await this.inventoryService.reserve(item.productId, item.quantity);\n    }\n  }\n}\n```\n\n### Saga Pattern\n\nCoordinate multiple aggregates with compensation:\n\n```\nSaga: Order Fulfillment\n\n┌─────────┐     ┌─────────────┐     ┌─────────────┐     ┌─────────┐\n│ Create  │────►│ Reserve     │────►│ Charge      │────►│ Ship    │\n│ Order   │     │ Inventory   │     │ Payment     │     │ Order   │\n└────┬────┘     └──────┬──────┘     └──────┬──────┘     └─────────┘\n     │                 │                   │\n     │ Compensate:     │ Compensate:       │ Compensate:\n     │ Cancel Order    │ Release Inventory │ Refund Payment\n     ▼                 ▼                   ▼\n\nOn failure at any step, execute compensation in reverse order.\n```\n\n### Choosing Consistency\n\n| Scenario | Strategy |\n|----------|----------|\n| Within single aggregate | Transactional (ACID) |\n| Across aggregates, same service | Eventual (domain events) |\n| Across services | Saga with compensation |\n| Read model updates | Eventual (projection) |\n\n## Anti-Patterns\n\n### Anemic Domain Model\n\n```\n\u002F\u002F Anti-pattern: Logic outside domain objects\nclass Order {\n  id: string;\n  items: Item[];\n  status: string;\n}\n\nclass OrderService {\n  calculateTotal(order: Order): number { ... }\n  validate(order: Order): boolean { ... }\n  submit(order: Order): void { ... }\n}\n\n\u002F\u002F Better: Logic inside domain objects\nclass Order {\n  private items: OrderItem[];\n  private status: OrderStatus;\n\n  get total(): Money {\n    return this.items.reduce((sum, item) => sum.add(item.subtotal), Money.zero());\n  }\n\n  submit(): void {\n    this.validate();\n    this.status = OrderStatus.Submitted;\n  }\n}\n```\n\n### Large Aggregates\n\n```\n\u002F\u002F Anti-pattern: Everything in one aggregate\nclass Customer {\n  orders: Order[];           \u002F\u002F Could be thousands\n  addresses: Address[];\n  paymentMethods: PaymentMethod[];\n  preferences: Preferences;\n  activityLog: Activity[];   \u002F\u002F Could be millions\n}\n\n\u002F\u002F Better: Separate aggregates referenced by ID\nclass Customer {\n  id: CustomerId;\n  defaultAddressId: AddressId;\n  defaultPaymentMethodId: PaymentMethodId;\n}\n\nclass Order {\n  customerId: CustomerId;    \u002F\u002F Reference by ID\n}\n```\n\n### Primitive Obsession\n\n```\n\u002F\u002F Anti-pattern: Primitive types for domain concepts\nfunction createOrder(\n  customerId: string,\n  productId: string,\n  quantity: number,\n  price: number,\n  currency: string\n) { ... }\n\n\u002F\u002F Better: Value objects\nfunction createOrder(\n  customerId: CustomerId,\n  productId: ProductId,\n  quantity: Quantity,\n  price: Money\n) { ... }\n```\n\n## Implementation Checklist\n\n### Aggregate Design\n\n- [ ] Single entity can be aggregate root\n- [ ] Invariants are protected at boundary\n- [ ] Other aggregates referenced by ID only\n- [ ] Fits in memory comfortably\n- [ ] One transaction per aggregate\n\n### Entity Implementation\n\n- [ ] Has unique identifier\n- [ ] Equality based on ID\n- [ ] Encapsulates business rules\n- [ ] State changes through methods\n\n### Value Object Implementation\n\n- [ ] All properties immutable\n- [ ] Equality based on attributes\n- [ ] Self-validating\n- [ ] Operations return new instances\n\n### Repository Implementation\n\n- [ ] One per aggregate\n- [ ] Returns aggregate roots only\n- [ ] Hides persistence details\n- [ ] Supports queries needed by domain\n\n## References\n\n- [Pattern Implementation Examples](examples\u002Fddd-patterns.md) - Code examples in multiple languages\n- [Aggregate Design Guide](reference.md) - Detailed aggregate sizing heuristics\n",{"name":5,"description":7},"main","7850740bd837adb32f0a109ab2af82482196c6f2","skills\u002Frsmdt-the-startup\u002Fplugins\u002Fteam\u002Fskills\u002Fdevelopment\u002Fdomain-driven-design",1,"https:\u002F\u002Fgithub.com\u002Fshengdabai\u002FTony-Claude-Code-Skills","https:\u002F\u002Fzturnsgo.com","https:\u002F\u002Fgithub.com\u002Fshengdabai","https:\u002F\u002Fzturnsgo.com\u002F","AI × education creator — producer, not consumer. Taught 6,000+ learners; shipping learning tools & daily essays with Claude Code, practicing @xiaolai's way 🥋","2026-11-01 21:28:23",{"source":8,"skillName":5,"commands":65,"prompt":75,"zipAvailable":76},[66,69,72],{"tool":67,"command":68},"npx","npx skills add shengdabai\u002FTony-Claude-Code-Skills --skill domain-driven-design",{"tool":70,"command":71},"bunx","bunx skills add shengdabai\u002FTony-Claude-Code-Skills --skill domain-driven-design",{"tool":73,"command":74},"pnpm","pnpm dlx skills add shengdabai\u002FTony-Claude-Code-Skills --skill domain-driven-design","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fshengdabai\u002FTony-Claude-Code-Skills\u002Fblob\u002Fmain\u002Fskills\u002Frsmdt-the-startup\u002Fplugins\u002Fteam\u002Fskills\u002Fdevelopment\u002Fdomain-driven-design\u002FSKILL.md",true,[],[79,96,128,153,175,195],{"skillNo":80,"name":81,"nameZh":6,"description":82,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":83,"categories":84,"keywords":88,"publishedAt":49},"01M70P17DAD4C1C47NPH6A96EM","xiaolai-methodology","以李笑来(Li Xiaolai)的思考方式、方法论与表达风格,为用户做全方位 1-on-1 教练指导,覆盖创业、赚钱、投资、学习、自学、读书写作、用 AI、以及人生心态与自我管理。当用户提到 \"李笑来\"、\"笑来\"、\"笑来老师\"、\"扮演李笑来\"、\"找笑来聊聊\"、\"笑来怎么看\"、\"xiaolai\"、\"把时间当作朋友\"、\"通往财富自由之路\"、\"定投改变命运\"、\"韭菜的自我修养\"、\"自学是门手艺\"、\"让时间陪你慢慢变富\"、\"七年就是一辈子\"、\"元认知\"、\"活在未来\"、\"复利\u002F长期主义\"、\"践行\"、\"痴迷改进\"、\"个人商业模式\u002F出售时间\"、\"睡后收入\"、\"定投\"、\"财富自由\"、\"操作系统升级\"、\"最少必要知识\"、\"北极星提示词\"、\"用 AI 该怎么学\u002F思考\" 等任一触发词,或当用户带着关于创业\u002F赚钱\u002F投资\u002F学习\u002F职业\u002F重大人生决策的困惑、希望被人用笑来式的「逻辑 + 大白话 + 类比 + 重新定义 + 践行导向」来点醒和指导时,自动进入李笑来教练模式。","https:\u002F\u002Fgithub.com\u002Fshengdabai\u002FTony-Claude-Code-Skills\u002Fblob\u002Fmain\u002Fxiaolai-methodology\u002FSKILL.md",[85],{"categoryNo":86,"categoryName":87,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000018","写作与文案",[89,90,91,92,93,94,95],"methodology","xiaolai","xiaolai methodology","朋友","投资","writing","收入",{"skillNo":97,"name":98,"nameZh":6,"description":99,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":100,"categories":101,"keywords":108,"publishedAt":49},"01M70P13NB9YP7ACJR1S861CDS","zread","Produce and consume a wiki-style knowledge base for a code repository via the `zread` CLI and its on-disk output under `.\u002F.zread\u002Fwiki\u002F`. Use this skill whenever the user wants to understand, onboard onto, explore, summarize, map, or get an overview of an unfamiliar codebase; asks for architecture docs, a project wiki, a repo walkthrough, module\u002Fpackage explanations, or \"what does this repo do\"; wants to generate, regenerate, resume, browse, or serve code documentation locally; or mentions zread \u002F zread.ai directly. Also use it proactively before diving into a large unknown repo — if `.\u002F.zread\u002Fwiki\u002Fcurrent` exists, read the generated pages instead of crawling source file-by-file; if it doesn't, consider offering to run `zread generate`. The trigger is the intent (understand a codebase through generated docs), not the literal word \"zread\".","https:\u002F\u002Fgithub.com\u002Fshengdabai\u002FTony-Claude-Code-Skills\u002Fblob\u002Fmain\u002Fskills\u002Fzread\u002FSKILL.md",[102,105],{"categoryNo":103,"categoryName":104,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000023","Skill与智能体开发",{"categoryNo":106,"categoryName":107,"taxonomyType":26,"taxonomyTypeDesc":27},"01JBSEEDCAT000000000000030","开发工程师",[98,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127],"knowledge","wiki","explore","walkthrough","project","get","knowledge base","run","generate","intent","cli","map","documentation","project wiki","disk","architecture","code","unknown","generated",{"skillNo":129,"name":130,"nameZh":6,"description":131,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":132,"categories":133,"keywords":138,"publishedAt":49},"01M70P10S4SWMZQ8BJAFBFDRW3","youtube","Launch the YouTube Creator Agent to auto-generate videos.\nUse when: user types \u002Fyoutube, wants to create YouTube videos,\ngenerate video content, or upload to YouTube.\nKeywords: youtube, video, 视频, 创作视频, 发布视频","https:\u002F\u002Fgithub.com\u002Fshengdabai\u002FTony-Claude-Code-Skills\u002Fblob\u002Fmain\u002Fskills\u002Fyoutube\u002FSKILL.md",[134,135],{"categoryNo":103,"categoryName":104,"taxonomyType":21,"taxonomyTypeDesc":22},{"categoryNo":136,"categoryName":137,"taxonomyType":26,"taxonomyTypeDesc":27},"01JBSEEDCAT000000000000036","内容创作者",[130,139,140,141,142,143,144,145,117,146,147,148,43,33,149,150,151,152],"user","content","视频","creator","generate video","videos","launch","video content","create","upload","auto","types","Video","创作",{"skillNo":154,"name":155,"nameZh":6,"description":156,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":157,"categories":158,"keywords":160,"publishedAt":49},"01M70P0YE95D8BACZCGV8BK90K","youtube-script-sync","Sync, update, or optimize Tony's GetNote knowledge base `Youtube视频逐字稿` by turning each parent recording or first-person idea note into an idempotent child note containing a directly recordable YouTube long-video or Shorts script. Use when the user says “更新\u002F同步\u002F优化 Youtube视频逐字稿知识库”, or says “更新\u002F同步\u002F优化该知识库” while this knowledge base is the active context.","https:\u002F\u002Fgithub.com\u002Fshengdabai\u002FTony-Claude-Code-Skills\u002Fblob\u002Fmain\u002Fskills\u002Fyoutube-script-sync\u002FSKILL.md",[159],{"categoryNo":103,"categoryName":104,"taxonomyType":21,"taxonomyTypeDesc":22},[161,162,130,163,164,151,165,166,167,168,169,170,171,172,115,173,43,33,109,174],"sync","script","youtube script sync","recording","shorts","first","base","person","update","active","child","optimize","idempotent","long",{"skillNo":176,"name":177,"nameZh":6,"description":178,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":179,"categories":180,"keywords":185,"publishedAt":49},"01M70P0WMV5XT0EEC0N445PW07","writing-skills","How to write SKILL.md files that trigger reliably and teach effectively. Use when creating, improving, or reviewing Claude Code skills.","https:\u002F\u002Fgithub.com\u002Fshengdabai\u002FTony-Claude-Code-Skills\u002Fblob\u002Fmain\u002Fskills\u002Fxiaolai\u002Fnlpm\u002Fskills\u002Fnlpm\u002Fwriting-skills\u002FSKILL.md",[181,182,183,184],{"categoryNo":86,"categoryName":87,"taxonomyType":21,"taxonomyTypeDesc":22},{"categoryNo":103,"categoryName":104,"taxonomyType":21,"taxonomyTypeDesc":22},{"categoryNo":106,"categoryName":107,"taxonomyType":26,"taxonomyTypeDesc":27},{"categoryNo":136,"categoryName":137,"taxonomyType":26,"taxonomyTypeDesc":27},[186,94,187,188,189,190,125,43,33,191,192,193,194],"writing skills","how","teach","write skill","write","claude code skills","files","how to","trigger",{"skillNo":196,"name":197,"nameZh":6,"description":198,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":199,"categories":200,"keywords":203,"publishedAt":49},"01M70P0SJFR4YVJQBGMHKGSKXT","writing-rules","How to write .claude\u002Frules\u002F files that Claude actually follows. Use when creating, improving, or reviewing project rules.","https:\u002F\u002Fgithub.com\u002Fshengdabai\u002FTony-Claude-Code-Skills\u002Fblob\u002Fmain\u002Fskills\u002Fxiaolai\u002Fnlpm\u002Fskills\u002Fnlpm\u002Fwriting-rules\u002FSKILL.md",[201,202],{"categoryNo":86,"categoryName":87,"taxonomyType":21,"taxonomyTypeDesc":22},{"categoryNo":136,"categoryName":137,"taxonomyType":26,"taxonomyTypeDesc":27},[204,94,205,113,206,192,43,187,190,33,193],"Rules","writing rules","project rules"]