Domain-Driven Development provides a systematic approach for refactoring existing codebases where behavior preservation is paramount. Unlike TDD which creates new functionality, DDD improves structure without changing behavior.
Test Type: Specification tests that define expected behavior
Outcome: New working code with test coverage
DDD Approach (for refactoring):
Cycle: ANALYZE-PRESERVE-IMPROVE
Goal: Improve structure without behavior change
Starting Point: Existing code with defined behavior
Test Type: Characterization tests that capture current behavior
Outcome: Better structured code with identical behavior
DDD方法(针对新功能):
循环:RED-GREEN-REFACTOR
目标:通过测试创建新功能
起点:无现有代码
测试类型:定义预期行为的规范测试
结果:带有测试覆盖率的可运行新代码
DDD方法(针对重构):
循环:ANALYZE-PRESERVE-IMPROVE
目标:在不改变行为的前提下改进结构
起点:带有既定行为的现有代码
测试类型:捕获当前行为的特征测试
结果:结构更优但行为完全一致的代码
Behavior Preservation Principle
行为保留原则
The golden rule of DDD is that observable behavior must remain identical before and after refactoring. This means:
All existing tests must pass unchanged
API contracts remain identical
Side effects remain identical
Performance characteristics remain within acceptable bounds
DDD的黄金准则是:重构前后的可观察行为必须完全一致。这意味着:
所有现有测试必须无修改通过
API契约保持完全一致
副作用保持完全一致
性能特征保持在可接受范围内
Implementation Guide
实施指南
Phase 1: ANALYZE
阶段1:ANALYZE
The analyze phase focuses on understanding the current codebase structure and identifying refactoring opportunities.
分析阶段专注于理解当前代码库结构并识别重构机会。
Domain Boundary Identification
领域边界识别
Identify logical boundaries in the codebase by examining:
Module dependencies and import patterns
Data flow between components
Shared state and coupling points
Public API surfaces
Use AST-grep to analyze structural patterns. For Python, search for import patterns to understand module dependencies. For class hierarchies, analyze inheritance relationships and method distributions.
Afferent Coupling (Ca): Number of classes depending on this module
Efferent Coupling (Ce): Number of classes this module depends on
Instability (I): Ce / (Ca + Ce) - higher means less stable
Abstractness (A): Abstract classes / Total classes
Distance from Main Sequence: |A + I - 1|
Low cohesion and high coupling indicate refactoring candidates.
评估代码质量指标:
传入耦合度(Ca):依赖此模块的类数量
传出耦合度(Ce):此模块依赖的类数量
不稳定性(I):Ce / (Ca + Ce) —— 值越高表示稳定性越差
抽象性(A):抽象类数量 / 总类数量
主序列距离:|A + I - 1|
低内聚度与高耦合度的模块是重构候选对象。
Structural Analysis Patterns
结构分析模式
Use AST-grep to identify problematic patterns:
God classes with too many methods or responsibilities
Feature envy where methods use other class data excessively
Long parameter lists indicating missing abstractions
Duplicate code patterns across modules
Create analysis reports documenting:
Current architecture overview
Identified problem areas with severity ratings
Proposed refactoring targets with risk assessment
Dependency graphs showing coupling relationships
使用AST-grep识别有问题的模式:
包含过多方法或职责的上帝类
方法过度使用其他类数据的特性羡慕问题
表示缺少抽象的长参数列表
跨模块的重复代码模式
创建分析报告,记录:
当前架构概述
带有严重程度评级的已识别问题区域
带有风险评估的拟议重构目标
展示耦合关系的依赖图
Phase 2: PRESERVE
阶段2:PRESERVE
The preserve phase establishes safety nets before making any changes.
保留阶段会在进行任何变更前建立安全网。
Characterization Tests
特征测试
Characterization tests capture existing behavior without assumptions about correctness. The goal is to document what the code actually does, not what it should do.
Steps for creating characterization tests:
Step 1: Identify critical code paths through execution
Step 2: Create tests that exercise these paths
Step 3: Let tests fail initially to discover actual output
Step 4: Update tests to expect actual output
Step 5: Document any surprising behavior discovered
Characterization test naming convention: testcharacterize[component]_[scenario]
特征测试捕获现有行为,不做正确性假设。目标是记录代码实际的行为,而非它应该有的行为。
创建特征测试的步骤:
步骤1:通过执行识别关键代码路径
步骤2:创建测试以覆盖这些路径
步骤3:让测试初始失败以发现实际输出
步骤4:更新测试以预期实际输出
步骤5:记录发现的任何意外行为
特征测试命名规范:testcharacterize[组件]_[场景]
Behavior Snapshots
行为快照
For complex outputs, use snapshot testing to capture current behavior:
API response snapshots
Serialization output snapshots
State transformation snapshots
Error message snapshots
Snapshot files serve as behavior contracts during refactoring.
对于复杂输出,使用快照测试捕获当前行为:
API响应快照
序列化输出快照
状态转换快照
错误消息快照
快照文件在重构期间充当行为契约。
Test Safety Net Verification
测试安全网验证
Before proceeding to improvement phase, verify:
All existing tests pass (100% green)
New characterization tests cover refactoring targets
Code coverage meets threshold for affected areas
No flaky tests exist in the safety net
Run mutation testing if available to verify test effectiveness.
进入改进阶段前,需验证:
所有现有测试均通过(100% 绿色)
新特征测试覆盖了重构目标
受影响区域的代码覆盖率达到阈值
安全网中不存在不稳定测试
若有可用工具,运行突变测试以验证测试的有效性。
Phase 3: IMPROVE
阶段3:IMPROVE
The improve phase makes structural changes while continuously validating behavior preservation.
改进阶段会在持续验证行为保留的前提下进行结构变更。
Incremental Transformation Strategy
增量转换策略
Never make large changes at once. Follow this pattern:
Make smallest possible structural change
Run full test suite
If tests fail, revert immediately
If tests pass, commit the change
Repeat until refactoring goal achieved
切勿一次性进行大规模变更。遵循以下模式:
进行最小的结构变更
运行完整测试套件
若测试失败,立即回滚
若测试通过,提交变更
重复直至达成重构目标
Safe Refactoring Patterns
安全重构模式
Extract Method: When a code block can be named and isolated. Use AST-grep to identify candidates by searching for repeated code blocks or long methods.
Extract Class: When a class has multiple responsibilities. Move related methods and fields to a new class while maintaining the original API through delegation.
Move Method: When a method uses data from another class more than its own. Relocate while preserving all call sites.
Inline Refactoring: When indirection adds complexity without benefit. Replace delegation with direct implementation.
Rename Refactoring: When names do not reflect current understanding. Update all references atomically using AST-grep rewrite.
提取方法:当代码块可被命名并隔离时使用。使用AST-grep识别重复代码块或长方法作为候选对象。
提取类:当一个类承担多个职责时使用。将相关方法和字段移至新类,同时通过委托保持原API。
移动方法:当方法更多使用其他类的数据而非自身类数据时使用。迁移方法的同时保留所有调用点。
内联重构:当间接性增加复杂度却无收益时使用。用直接实现替代委托。
重命名重构:当名称无法反映当前认知时使用。使用AST-grep重写工具批量更新所有引用。
AST-Grep Assisted Transformations
AST-Grep辅助转换
Use AST-grep for safe, semantic-aware transformations:
For method extraction, create a rule that identifies the code pattern and rewrites to the extracted form.
For API migration, create a rule that matches old API calls and rewrites to new API format.
For deprecation handling, create rules that identify deprecated patterns and suggest modern alternatives.
使用AST-grep进行安全的、语义感知的转换:
对于方法提取,创建规则识别代码模式并重写为提取后的形式。
对于API迁移,创建规则匹配旧API调用并重写为新API格式。
对于弃用处理,创建规则识别已弃用模式并建议现代替代方案。
Continuous Validation Loop
持续验证循环
After each transformation:
Run unit tests (fast feedback)
Run integration tests (behavior validation)
Run characterization tests (snapshot comparison)
Verify no new warnings or errors introduced
Check performance benchmarks if applicable
每次转换后:
运行单元测试(快速反馈)
运行集成测试(行为验证)
运行特征测试(快照对比)
验证未引入新的警告或错误
若适用,检查性能基准
DDD Workflow Execution
DDD工作流执行
Standard DDD Session
标准DDD会话
When executing DDD through moai:2-run in DDD mode:
Step 1 - Initial Assessment:
Read SPEC document for refactoring scope
Identify affected files and components
Assess current test coverage
Step 2 - Analyze Phase Execution:
Run AST-grep analysis on target code
Generate coupling and cohesion metrics
Create domain boundary map
Document refactoring opportunities
Step 3 - Preserve Phase Execution:
Verify all existing tests pass
Create characterization tests for uncovered paths
Generate behavior snapshots
Confirm safety net adequacy
Step 4 - Improve Phase Execution:
Execute transformations incrementally
Run tests after each change
Commit successful changes immediately
Document any discovered issues
Step 5 - Validation and Completion:
Run full test suite
Compare before/after metrics
Verify all behavior snapshots match
Generate refactoring report
通过moai:2-run以DDD模式执行DDD时:
步骤1 - 初始评估:
阅读SPEC文档了解重构范围
识别受影响的文件与组件
评估当前测试覆盖率
步骤2 - 分析阶段执行:
对目标代码运行AST-grep分析
生成耦合度与内聚度指标
创建领域边界图
记录重构机会
步骤3 - 保留阶段执行:
验证所有现有测试通过
为未覆盖路径创建特征测试
生成行为快照
确认安全网足够可靠
步骤4 - 改进阶段执行:
增量执行转换
每次变更后运行测试
立即提交成功的变更
记录发现的任何问题
步骤5 - 验证与完成:
运行完整测试套件
对比变更前后的指标
验证所有行为快照匹配
生成重构报告
DDD Loop Pattern
DDD循环模式
For complex refactoring requiring multiple iterations:
Set maximum loop iterations based on scope
Each loop focuses on one refactoring target
Exit conditions: all targets adddessed or iteration limit reached
Progress tracking through TODO list updates
针对需要多次迭代的复杂重构:
根据范围设置最大循环迭代次数
每个循环专注于一个重构目标
退出条件:所有目标完成或达到迭代上限
通过更新TODO列表跟踪进度
Quality Metrics
质量指标
DDD Success Criteria
DDD成功标准
Behavior Preservation (Required):
All pre-existing tests pass
All characterization tests pass
No API contract changes
Performance within bounds
Structure Improvement (Goals):
Reduced coupling metrics
Improved cohesion scores
Reduced code complexity
Better separation of concerns
行为保留(必填):
所有预先存在的测试通过
所有特征测试通过
无API契约变更
性能在可接受范围内
结构改进(目标):
耦合度指标降低
内聚度得分提升
代码复杂度降低
关注点分离更清晰
DDD-Specific TRUST Validation
DDD专属TRUST验证
Apply TRUST 5 framework with DDD focus:
Testability: Characterization test coverage adequate
Readability: Naming and structure improvements verified
Understandability: Domain boundaries clearer
Security: No new vulnerabilities introduced
Transparency: All changes documented and traceable
针对DDD应用TRUST 5框架:
可测试性:特征测试覆盖率足够
可读性:命名与结构改进已验证
可理解性:领域边界更清晰
安全性:未引入新漏洞
透明度:所有变更均已记录且可追溯
Integration Points
集成点
With AST-Grep Skill
与AST-Grep Skill集成
DDD relies heavily on AST-grep for:
Structural code analysis
Pattern identification
Safe code transformations
Multi-file refactoring
Load moai-tool-ast-grep for detailed pattern syntax and rule creation.
DDD严重依赖AST-grep实现:
结构化代码分析
模式识别
安全代码转换
多文件重构
加载moai-tool-ast-grep以获取详细的模式语法与规则创建方法。
With Testing Workflow
与测试工作流集成
DDD complements testing workflow:
Uses characterization tests from testing patterns
Integrates with mutation testing for safety net validation
Leverages snapshot testing infrastructure
DDD与测试工作流互补:
使用测试模式中的特征测试
集成突变测试以验证安全网
利用快照测试基础设施
With Quality Framework
与质量框架集成
DDD outputs feed into quality assessment:
Before/after metrics comparison
TRUST 5 validation for changes
Technical debt tracking
DDD输出可用于质量评估:
变更前后指标对比
针对变更的TRUST 5验证
技术债务跟踪
Troubleshooting
故障排除
Common Issues
常见问题
Tests Fail After Transformation:
Revert immediately to last known good state
Analyze which tests failed and why
Check if transformation changed behavior unintentionally
Consider smaller transformation steps
Characterization Tests Are Flaky:
Identify sources of non-determinism
Mock external dependencies
Fix time-dependent or order-dependent behavior
Consider snapshot tolerance settings
Performance Degradation:
Profile before and after
Identify hot paths affected by changes
Consider caching or optimization
Document acceptable trade-offs
转换后测试失败:
立即回滚至最后已知的稳定状态
分析测试失败的原因
检查转换是否意外改变了行为
考虑采用更小的转换步骤
特征测试不稳定:
识别非确定性来源
模拟外部依赖
修复时间依赖或顺序依赖的行为
考虑调整快照容差设置
性能下降:
对比变更前后的性能分析结果
识别受变更影响的热点路径
考虑缓存或优化方案
记录可接受的权衡
Recovery Procedures
恢复流程
When DDD session encounters issues:
Save current state with git stash
Reset to last successful commit
Review transformation that caused failure
Plan alternative approach
Resume from preserved state
Version: 1.0.0
Status: Active
Last Updated: 2026-01-16