测试设计
- 作者仓库星标 0
- 作者更新于 实时读取
- 作者仓库 skills-registry
- 领域
- 设计与多媒体
- 兼容 Agent
-
- Claude Code
- Cursor
- Cline
- Codex
- Windsurf
- Gemini CLI
- +20
- 信任分
- 88 / 100 · 社区维护
- 作者 / 版本 / 许可
- @tomevault-io · 未声明 license
- Token 消耗评级
- 中等消耗
- 接入复杂程度
- 需简单配置
- 是否需要外部 API Key
- 不需要
- 兼容的系统
- 未声明(默认跨平台)
- 底层运行要求
- 无特殊要求
- 文件与系统权限
-
- 只读
- 允许写入 / 修改
- 网络行为
- 仅限本地
- 安装命令数
- 26 条
档案由构建时根据 SKILL.md 与安装命令自动衍生,可能与作者实际意图存在差异。
需要注意: 未限定 allowed-tools,默认拥有全部工具权限。
---
name: domain-driven-design
description: Domain-Driven Design patterns for TypeScript. Use when implementing ubiquitous language, value o…
category: 设计与多媒体
runtime: 无特殊运行时
---
# domain-driven-design 输出预览
## PART A: 任务判断
- 适用问题:视觉内容、演示材料、信息图或设计交付。
- 输入要求:目标材料、限制条件、期望输出和验收方式。
- 证据边界:围绕“When to Use DDD / Core Principle / Where Does This Code Belong?”读取原文规则,不把推断写成作者承诺。
## PART B: 执行结果
- **01** 任务判断:确认你的需求是否属于视觉内容、演示材料、信息图或设计交付,并标出输入、限制和预期结果。
- **02** 执行计划:优先按“When to Use DDD / Core Principle / Where Does This Code Belong?”拆成步骤,说明每一步会读取什么、修改什么、产出什么。
- **03** 交付结果:给出可复制的命令、文件改动、检查清单或内容草稿,并说明如何继续迭代。
- **04** 风险边界:结合 读取文件、写入/修改文件、主要在本地完成、通常不需要额外 API Key 给出执行前确认项。
## Running Rules
- 读取文件、写入/修改文件;主要在本地完成;通常不需要额外 API Key。
- 先小样例验证,再放大到真实任务。
- 交付时同时给结果、检查口径和下一步迭代建议。 原文没有稳定的斜杠命令要求。安装验证后通常全局生效,直接在对话里点名这个 Skill 并描述任务即可。
告诉 Agent 目标文件或材料、期望结果、不可改范围、是否允许联网或执行命令。本 Skill 的权限画像是:读取文件、写入/修改文件。
先用一个小任务确认它会围绕“When to Use DDD / Core Principle / Where Does This Code Belong?”工作;涉及文件或命令时,先看 diff、日志、预览或测试结果。
检查最终产物是否包含明确结果、必要证据和下一步动作;如果输出泛泛而谈,就补充输入、边界和验收标准后重跑。
---
name: domain-driven-design
description: Domain-Driven Design patterns for TypeScript. Use when implementing ubiquitous language, value o…
category: 设计与多媒体
source: tomevault-io/skills-registry
---
# domain-driven-design
## 什么时候使用
- 把设计与视觉方向的常用动作沉淀成 Agent 可调用的技能 适合处理界面、视觉、封面、信息图或演示材料交付,核心价值是把输入、判断、执行、验证和交付边界固定下来,避免 Agent 泛泛回答。 把任务拆成可执行、可检查、可继续迭代的步骤…
- 面向视觉内容、演示材料、信息图或设计交付,优先处理能明确输入、步骤和验收标准的工作。
## 需要提供什么
- 目标材料、目录范围、期望结果和不可改动内容。
- 是否允许联网、执行命令、读写文件或调用外部服务。
## 执行规则
- 围绕「When to Use DDD / Core Principle / Where Does This Code Belong?」组织步骤,不把推断写成作者事实。
- 读取文件、写入/修改文件;主要在本地完成;通常不需要额外 API Key。
- 先跑小样例,确认结果可检查后再扩大任务范围。
## 输出要求
- 给出最终产物、关键证据、验证方式和下一步动作。
- 信息不足时标记 unknown,不编造命令、平台或依赖。 作者原文负责流程事实;仓库文件负责来源和命令;流狐只补充适用场景、限制和质量判断。
skill "domain-driven-design" {
输入层 -> 用户目标 + 目标文件 + 禁止范围 + 验收标准
上下文层 -> When to Use DDD / Core Principle / Where Does This Code Belong?
规则层 -> SKILL.md 触发条件 / 执行顺序 / 输出格式
运行层 -> 无特殊运行时 | 读取文件、写入/修改文件 | 主要在本地完成
安全层 -> 通常不需要额外 API Key + 小任务验证 + diff / 日志复核
输出层 -> 可复制结果 + 检查清单 + 下一步迭代
} Domain-Driven Design (DDD)
This skill applies only to projects that have opted in to DDD. Do not apply these patterns to projects that use a different approach.
For hexagonal architecture (ports and adapters), load the hexagonal-architecture skill. DDD and hexagonal architecture are complementary but independent — a project may use one without the other.
Deep-dive resources are in the resources/ directory. Load them on demand:
| Resource | Load when... |
|---|---|
aggregate-design.md |
Designing or splitting aggregates, sizing questions, optimistic locking |
domain-services.md |
Unsure if logic is a domain service vs use case, naming conventions |
domain-events.md |
Cross-aggregate coordination, Decider pattern, event dispatch (outbox), process managers |
bounded-contexts.md |
Drawing context boundaries, integrating with external systems (ACL), context mapping |
error-modeling.md |
Deciding between result types and exceptions, error propagation |
testing-by-layer.md |
Writing tests for DDD code, property-based testing for invariants |
For authoritative sources, see ../REFERENCES.md.
When to Use DDD
DDD adds value for complex domains with rich business rules. Not every project needs it.
Use DDD when:
- Domain has complex business rules and invariants
- Multiple stakeholders with domain expertise
- Business logic is the core differentiator
- Terms have specific, important meanings
Don't use DDD when:
- Simple CRUD with no business rules
- Technical/infrastructure-focused projects
- No domain expert to consult
Start simple and evolve: Begin with ubiquitous language (glossary) and value objects. Add aggregates, domain events, and bounded contexts only when the domain demands it. Your first model will be wrong — that's fine. The goal is to learn quickly and refactor toward deeper insight.
Core Principle
The code must speak the language of the domain. Every type, function, variable, and test name must use terms from the project's ubiquitous language (glossary). If a concept doesn't have a domain term, that's a modeling gap to discuss with stakeholders — not something to paper over with technical jargon.
Domain models evolve. The first model is never the final model. As understanding deepens through conversations with domain experts and building working software, the model should change — types get renamed, aggregates get split or merged, new concepts emerge. This is expected and ideal. A model that never changes is either perfect (unlikely) or stagnant (the team stopped learning). TDD and behavioral tests make this evolution safe — rename a concept, update the glossary, and the tests tell you what needs to change.
Where Does This Code Belong?
This is the most common decision in DDD. When unsure, use this framework:
| Question | If yes → | If no ↓ |
|---|---|---|
| Does it enforce a business rule or compute a business value? | domain/ (entity function, value object, or domain service) |
↓ |
| Does it orchestrate multiple domain operations without owning logic? | Use case / application service | ↓ |
| Does it format, transform, or prepare data for display? | lib/ or inline in the view |
↓ |
| Does it talk to an external system (DB, API, file system)? | Adapter (implements a port defined in domain) | ↓ |
| Is it framework-specific glue (route handler, middleware)? | Delivery layer (app/) |
— |
The purity test is necessary but not sufficient. A pure function that formats a date for display does not belong in domain/ just because it's pure. The question is always: "Is this a business rule?"
// ❌ Pure but NOT domain — formats for human display
export const formatEventDate = (date: string | null) =>
date ? format(parseISO(date), "MMMM d, yyyy") : undefined;
// → Belongs in lib/format.ts
// ✅ Pure AND domain — business rule that affects behavior
export const isPastEvent = (eventDate: string | null, now: Date) =>
eventDate ? parseISO(eventDate) < now : false;
// → Belongs in domain/event/
// ✅ Pure AND domain — business calculation
export const calculateCommittedTotal = (items: readonly GiftItem[]) =>
items.filter(i => i.status !== "idea").reduce((sum, i) => sum + i.pricePence, 0);
// → Belongs in domain/budget/
Why placement matters: domain/ files typically have strict coverage requirements and zero infrastructure imports. Putting code in the wrong layer creates unnecessary testing obligations and architectural violations.
Ubiquitous Language & Glossary
DDD projects must maintain a glossary file that defines all domain terms. This is the single source of truth for naming. The glossary evolves as the model evolves — when the team discovers a better name or splits a concept, update the glossary first and let the code follow.
The Glossary File
For projects with multiple bounded contexts, organize by context. The same term may have different definitions in different contexts — this is correct, not a bug.
## Gifting Context
| Term | Definition | Examples |
|------|-----------|----------|
| Occasion | A gift-giving event (birthday, holiday) | "Mum's Birthday", "Christmas 2026" |
| Gift Idea | A potential gift for an occasion | "Cookbook", "Scarf" |
| Contribution | Money pledged toward a gift | "£25 from Dad" |
## Notifications Context
| Term | Definition | Examples |
|------|-----------|----------|
| Occasion | An upcoming event that may trigger reminders | (same events, different concern) |
| Recipient | The person being gifted — target of reminder scheduling | "Mum" |
Enforcement Rules
- All
typeandinterfacenames must use glossary terms - All function names must use glossary verbs and nouns
- All test descriptions must use domain language
- If you need a new term, add it to the glossary first
// ✅ Uses domain language
type GiftIdea = {
readonly id: GiftIdeaId;
readonly description: string;
readonly occasion: OccasionId;
readonly estimatedCost: Money;
};
// ❌ Technical jargon
type Item = { readonly id: string; readonly text: string; readonly parentId: string; };
Building Blocks
Value Objects
Immutable, identity-less, compared by their attributes (not by reference). Represent domain concepts defined by their attributes. Two Money values with the same amount and currency are equal — value objects have no identity.
type Currency = 'GBP' | 'USD' | 'EUR';
type Money = { readonly amount: number; readonly currency: Currency };
const createMoney = (amount: number, currency: Currency): Money => {
if (amount < 0) throw new Error('Money cannot be negative');
return { amount, currency };
};
// Factory throws = invariant violation (a bug in calling code).
// Schemas catch invalid user input at trust boundaries BEFORE
// the factory is called. If the factory throws, something
// bypassed the schema.
For value objects crossing trust boundaries (API input, form data), use Zod schemas. For domain-internal value objects, plain types + factory functions suffice. See the typescript-strict skill for schema-first patterns.
Zod-to-branded-type bridging — parse raw input into branded domain types at trust boundaries:
// Schema at trust boundary — parses raw strings into branded types
const PledgeInputSchema = z.object({
occasionId: z.string().min(1).transform(createOccasionId),
contributorId: z.string().min(1).transform(createContributorId),
amount: z.object({ amount: z.number().positive(), currency: CurrencySchema }),
});
// Reconstitution from persistence — same pattern, used in driven adapters
const toOccasion = (row: OccasionRow): Occasion => ({
id: createOccasionId(row.id),
name: row.name,
budget: createMoney(row.budgetAmount, parseCurrency(row.budgetCurrency)),
totalPledged: createMoney(row.pledgedAmount, parseCurrency(row.budgetCurrency)),
isFundingClosed: row.isFundingClosed,
});
Reconstitution (rebuilding domain objects from DB rows) uses the same factory functions as creation. The factory validates, so invalid persisted data is caught on read rather than silently corrupting the domain.
Branded Types
Prevent accidental swapping of primitives at compile time. Use for entity IDs and single-value value objects. Always provide a factory function — raw strings become branded types only through validation:
type OccasionId = string & { readonly __brand: 'OccasionId' };
type GiftIdeaId = string & { readonly __brand: 'GiftIdeaId' };
type EmailAddress = string & { readonly __brand: 'EmailAddress' };
// Factory functions — the only way to create branded values
const createOccasionId = (raw: string): OccasionId => {
if (!raw.trim()) throw new Error('OccasionId cannot be empty');
return raw as OccasionId; // justified: factory validates, then brands
};
const createEmailAddress = (raw: string): EmailAddress => {
if (!raw.includes('@')) throw new Error('Invalid email');
return raw as EmailAddress; // justified: factory validates, then brands
};
The as assertion is the one justified exception in branded type factories — the factory validates first, then brands. This is the standard TypeScript pattern for nominal typing. Everywhere else, the compiler prevents mixing up OccasionId and GiftIdeaId.
Entities
Have identity and a lifecycle. Always valid after construction or state transition.
type Occasion = {
readonly id: OccasionId;
readonly name: string;
readonly date: Date;
readonly giftIdeas: ReadonlyArray<GiftIdea>;
readonly budget: Money;
};
// Immutable update — returns new valid state
const renameOccasion = (occasion: Occasion, newName: string): Occasion => ({
...occasion,
name: newName,
});
Always-valid principle: An entity must satisfy its invariants at all times. Validate on construction (factory functions or schema parsing) and on every state transition. Never allow an entity to exist in an invalid state, even temporarily.
Make Illegal States Unrepresentable
Use the type system to make invalid states impossible. Replace boolean flags and optional fields with discriminated unions where each variant carries only the data valid for that state:
// WRONG — boolean + optional allows { isVerified: true, verifiedAt: undefined }
type User = { readonly isVerified: boolean; readonly verifiedAt?: Date };
// RIGHT — impossible to be verified without a date
type User =
| { readonly status: 'unverified' }
| { readonly status: 'verified'; readonly verifiedAt: Date };
Apply the same principle to entity lifecycles:
type Order =
| { readonly status: 'draft'; readonly items: ReadonlyArray<OrderItem> }
| { readonly status: 'placed'; readonly items: ReadonlyArray<OrderItem>; readonly placedAt: Date }
| { readonly status: 'shipped'; readonly items: ReadonlyArray<OrderItem>; readonly placedAt: Date; readonly shippedAt: Date; readonly trackingNumber: string };
Always handle all variants exhaustively. The never type ensures the compiler catches unhandled states when you add a new variant:
const describeOrder = (order: Order): string => {
switch (order.status) {
case 'draft': return `Draft with ${order.items.length} items`;
case 'placed': return `Placed at ${order.placedAt.toISOString()}`;
case 'shipped': return `Shipped: ${order.trackingNumber}`;
default: { const _exhaustive: never = order; return _exhaustive; }
}
};
Aggregates
Clusters of entities and value objects with a single root. All modifications go through the root.
- One aggregate root per transaction
- Reference other aggregates by ID — never embed
- All invariants enforced by the root
- Keep aggregates small — only what's needed for consistency
For detailed aggregate design guidance, see resources/aggregate-design.md.
Specifications (Predicate Functions)
Complex business rules for filtering, eligibility, or validation are expressed as predicate functions in the domain layer. Evans calls these "specifications."
// Specification: "can this contributor pledge to this occasion?"
const canPledge = (occasion: Occasion, contributor: Contributor, amount: Money): boolean =>
!occasion.isFundingClosed &&
amount.amount <= contributor.walletBalance.amount &&
amount.currency === occasion.budget.currency;
// Compose specifications for complex eligibility
const isGiftReady = (occasion: Occasion): boolean =>
occasion.totalPledged.amount >= occasion.budget.amount &&
occasion.giftIdeas.some(idea => idea.status === 'selected');
Specifications are pure predicate functions — they return boolean and have no side effects. Use them in domain services, use cases, and query filters. Name them with is, can, or has prefixes.
Domain Events
Domain events represent something meaningful that happened in the domain ("OrderPlaced", "ContributionPledged"). They coordinate side effects across aggregates and bounded contexts.
Domain events earn their complexity when:
- Side effects cross aggregate boundaries
- Other bounded contexts need to react to changes
- You need an audit trail or event-driven workflows
Don't add domain events when:
- All logic is within a single aggregate
- Side effects are within the same transaction
- Explicit return values from domain functions suffice
For most projects, start without domain events and add them when the domain demands coordination. See resources/domain-events.md for the Decider pattern and detailed guidance.
Domain Services
When business logic doesn't belong to a single entity, it belongs in a domain service — a stateless function in the domain layer that operates across multiple entities or aggregates.
// ❌ WRONG — cramming cross-entity logic into one entity
const addContribution = (occasion: Occasion, contribution: Contribution): Occasion => {
// This needs to check the contributor's wallet balance — wrong aggregate!
};
// ✅ CORRECT — domain service operates across aggregates
const pledgeContribution = (
occasion: Occasion,
contributor: Contributor,
amount: Money,
): PledgeResult => {
if (amount.amount > contributor.walletBalance.amount) {
return { success: false, reason: 'insufficient-balance' };
}
return {
success: true,
occasion: addContribution(occasion, { contributorId: contributor.id, amount }),
contributor: deductBalance(contributor, amount),
};
};
Domain service vs use case (application service):
| Domain Service | Use Case | |
|---|---|---|
| Contains business logic? | Yes | No — orchestration only |
| Lives in | domain/ |
domain/ — identifiable by taking ports as params |
| Depends on | Domain types only | Repositories, ports, domain services |
| Example | pledgeContribution(occasion, contributor, amount) |
handlePledge(repo, dto) — loads, calls domain service, saves |
For detailed guidance, see resources/domain-services.md.
Error Modeling
Use discriminated union result types for expected business outcomes. Reserve exceptions for programmer mistakes and infrastructure failures.
type PledgeResult =
| { readonly success: true; readonly occasion: Occasion; readonly contributor: Contributor }
| { readonly success: false; readonly reason: 'insufficient-balance' | 'funding-closed' | 'not-found' };
The test: Could a user's action legitimately cause this outcome? If yes → result type. If no (it would mean a bug) → exception.
For detailed error modeling patterns and how errors propagate through layers, see resources/error-modeling.md.
Repository Pattern
Repositories provide collection-like access to aggregates. Interfaces in the domain layer, implementations in the adapter layer. Repositories use interface (not type) because they define behavior contracts — this aligns with the TypeScript strict rule "reserve interface for behavior contracts." Name methods using domain language.
// Port (domain layer) — interface because it's a behavior contract
interface OccasionRepository {
readonly findById: (id: OccasionId) => Promise<Occasion | undefined>;
readonly save: (occasion: Occasion) => Promise<void>;
}
// Adapter (infrastructure layer) — see hexagonal-architecture skill
Repositories handle writes and single-aggregate reads. For reads that need to JOIN across aggregates (dashboard views, detail pages combining data from multiple entities), repositories are the wrong tool — they enforce aggregate boundaries that reads need to cross. Use query functions that JOIN freely instead. This is the CQRS-lite pattern: writes go through repositories (consistency), reads go through query functions (flexibility). See the hexagonal-architecture skill's CQRS-lite section and resources/cqrs-lite.md for details.
For simple domains where reads map cleanly to a single aggregate, repository reads are fine. Don't separate prematurely.
DDD + TDD Integration
Test by Domain Concept, Not Implementation File
tests/
occasions/
create-occasion.test.ts # Behavior: creating occasions
add-gift-idea.test.ts # Behavior: managing gift ideas
occasion-budget.test.ts # Behavior: budget constraints
Primary Test Boundary: The Use Case
Test by calling use cases with driven ports replaced by in-memory fakes (not mocks). This exercises domain entities, domain services, and orchestration together — proving the feature works as a whole.
Domain unit tests complement use case tests for complex pure business rules. They don't replace them.
| Priority | Boundary | What it proves |
|---|---|---|
| Primary | Use case (faked driven ports) | Feature works end-to-end within the hexagon |
| Complement | Domain pure functions directly | Complex business rules in isolation |
| Secondary | Driven adapters (real DB/MSW) | Adapter translates correctly |
| Verification | E2E (full stack) | User experience works |
For detailed testing guidance, see resources/testing-by-layer.md. For a complete worked example showing one feature through every layer with tests, see the hexagonal-architecture skill's resources/worked-example.md.
Test Factories Use Domain Language
const getTestOccasion = (overrides?: Partial<Occasion>): Occasion =>
OccasionSchema.parse({
id: createOccasionId('occasion-1'),
name: "Mum's Birthday",
giftIdeas: [],
budget: createMoney(100, 'GBP'),
...overrides,
});
Bounded Contexts
A bounded context is a linguistic boundary within which a particular domain model and glossary apply. The same word (e.g., "User") can mean different things in different contexts — and that's correct.
- Each context owns its own model and glossary —
Userin billing differs fromUserin shipping - Communicate between contexts via events or explicit contracts — never share mutable state
- Anti-Corruption Layer (ACL) — when integrating with external systems or other contexts whose model doesn't fit yours, translate at the boundary rather than letting their types leak in
- Shared kernel should be minimal — only truly universal value objects (Money, Email). If the shared kernel grows, boundaries are unclear
- Each context has its own glossary section
For context mapping patterns, monorepo structure, and ACL examples, see resources/bounded-contexts.md.
Anti-Patterns
Anemic Domain Model
Entities are data bags with no behavior. All logic in "services." Fix: put behavior as pure functions next to the types they operate on.
Generic Technical Names
Using Item, Entity, Record, Data, Info instead of domain terms. Always use the glossary.
Presentation Logic in Domain
Display formatting does not belong in domain/. The test: "make this look right for a human" = presentation (lib/). "Enforce a business rule" = domain. Purity is not sufficient — a pure formatting function is still presentation.
Leaking Domain Logic
Business logic in route handlers, database queries, or adapters. Keep it in domain/.
Over-Engineering
Not every project needs aggregates, domain events, or bounded contexts. Start with:
- Ubiquitous language (glossary)
- Value objects and entities
- Add complexity only when the domain demands it
Resisting Model Evolution
Treating the initial model as sacred — refusing to rename types, split aggregates, or restructure bounded contexts as understanding deepens. The model should evolve continuously. If a refactoring reveals that "Occasion" should really be "GiftEvent" and "SavingsGoal", do it. The glossary changes, the types change, the tests guide the migration. Evans calls these "breakthroughs" — moments where the model fundamentally improves because the team learned something new about the domain.
Checklist
- Glossary file exists and is up to date
- All types use glossary terms
- All functions use glossary verbs and nouns
- All test descriptions use domain language
- Value objects are immutable and identity-less
- Entities are always valid (invariants enforced on construction and transitions)
- Entities have branded IDs; primitive value objects use branded types
- Aggregate roots enforce all invariants
- Other aggregates referenced by ID, not embedded
- Cross-aggregate logic in domain services, not crammed into one entity
- Repository interfaces defined in domain layer
- Discriminated unions have exhaustive switch handling
- Expected business outcomes use result types, not exceptions
- Domain logic has zero infrastructure dependencies
- Presentation logic is NOT in domain/ (even if pure)
- Tests organized by domain concept, not implementation file
- Each layer has behavioral tests at the appropriate level
Source: citypaul/.dotfiles — distributed by TomeVault.
先判断是否适合
作者设计意图
作者的方法与取舍
边界和复核