Improve the code structure without changing external behavior.
在不改变外部行为的前提下优化代码结构。
Step 1 — Understand the Goal
步骤1 — 明确目标
Ask or infer:
What is wrong with the current code? (too long, duplicated, wrong layer, hard to test)
What is the desired outcome? (extracted function, renamed variable, moved to correct layer)
Are there tests in place? (if not, write characterization tests before refactoring)
询问或推断:
当前代码存在哪些问题?(过长、重复、层级错误、难以测试)
期望达成什么结果?(提取函数、重命名变量、移至正确层级)
是否已有测试用例?(如果没有,在重构前编写特征测试)
Step 2 — Establish a Safety Net
步骤2 — 构建安全保障
Before changing anything, verify tests exist that cover the code being refactored.
If tests are missing, write characterization tests first:
A characterization test captures current behavior (even if the behavior is wrong).
It prevents accidental behavior changes during refactoring.
在进行任何修改前,确认待重构代码已有测试覆盖。
如果缺少测试,先编写特征测试:
特征测试会捕捉当前行为(即使该行为是错误的)。
它能防止重构过程中意外改变行为。
Step 3 — Apply Refactoring in Small Steps
步骤3 — 分步实施重构
Work in small, safe increments. After each step, verify tests still pass:
Common refactoring moves:
Extract function/method: identify a coherent chunk of logic with a clear purpose.
Rename: choose a name that accurately describes the thing at the current abstraction level.
Move to correct layer: domain logic in a controller → move to use case or domain service.
Replace conditional with polymorphism: complex switch/if chains on type → strategy pattern.
Introduce value object: raw primitive used to represent a domain concept → wrap it.
Remove duplication: extract shared logic to a shared function; do not abstract prematurely.
以小步、安全的增量方式推进。每完成一步,验证测试仍能通过:
常见重构操作:
提取函数/方法:识别出具有明确用途的连贯逻辑块。
重命名:选择能准确描述当前抽象层级下事物的名称。
移至正确层级:将控制器中的领域逻辑移至用例或领域服务。
用多态替代条件语句:将基于类型的复杂switch/if链替换为策略模式。
引入值对象:将用于表示领域概念的原始基础类型进行封装。
消除重复:将共享逻辑提取到共享函数中;避免过早抽象。
Step 4 — Verify Behavior is Unchanged
步骤4 — 验证行为未改变
After refactoring:
All tests pass.
The public API (exported signatures) is unchanged.
No new dependencies introduced.
重构完成后:
所有测试通过。
公共API(导出签名)保持不变。
未引入新依赖。
Step 5 — Summarize
步骤5 — 总结
undefined
undefined
Refactor Summary
Refactor Summary
What changed: [List of moves applied]
Why: [The design problem that was addressed]
Tests: [Pass / added N new characterization tests]
Breaking changes: None (internal only)
undefined
What changed: [List of moves applied]
Why: [The design problem that was addressed]
Tests: [Pass / added N new characterization tests]
Breaking changes: None (internal only)