refactoring-patterns
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseRefactoring Patterns
重构模式
<default_to_action>
When refactoring:
- ENSURE tests pass (never refactor without tests)
- MAKE small change (one refactoring at a time)
- RUN tests (must stay green)
- COMMIT (save progress)
- REPEAT
Safe Refactoring Cycle:
bash
npm test # Green ✅<default_to_action>
进行重构时:
- 确保测试通过(绝不要在没有测试的情况下重构)
- 做出微小改动(一次只进行一项重构)
- 运行测试(必须保持绿灯状态)
- 提交(保存进度)
- 重复
安全重构循环:
bash
npm test # Green ✅Make ONE small change
Make ONE small change
npm test # Still green ✅
git commit -m "refactor: extract calculateTotal"
npm test # Still green ✅
git commit -m "refactor: extract calculateTotal"
Repeat
Repeat
**Code Smells → Refactoring:**
| Smell | Refactoring |
|-------|-------------|
| Long method (>20 lines) | Extract Method |
| Large class | Extract Class |
| Long parameter list (>3) | Introduce Parameter Object |
| Duplicated code | Extract Method/Class |
| Complex conditional | Decompose Conditional |
| Magic numbers | Named Constants |
| Nested loops | Replace Loop with Pipeline |
**NEVER REFACTOR:**
- Without tests (write tests first)
- When deadline is tomorrow
- Code you don't understand
- Code that works and won't be touched
</default_to_action>
**代码异味 → 重构方案:**
| 代码异味 | 重构方案 |
|---------|---------|
| 过长方法(超过20行) | 提取方法 |
| 过大类 | 提取类 |
| 过长参数列表(超过3个) | 引入参数对象 |
| 重复代码 | 提取方法/类 |
| 复杂条件判断 | 分解条件 |
| 魔法数值 | 命名常量 |
| 嵌套循环 | 用管道操作替代循环 |
**绝对不要在以下情况重构:**
- 没有测试(先编写测试)
- 明天就要截止交付时
- 你不理解的代码
- 运行正常且不会再被修改的代码
</default_to_action>Quick Reference Card
快速参考卡片
Common Refactorings
常见重构方式
| Pattern | Before | After |
|---|---|---|
| Extract Method | 50-line function | 5 small functions |
| Extract Class | Class doing 5 things | 5 single-purpose classes |
| Parameter Object | | |
| Replace Conditional | | Polymorphism |
| Pipeline | Nested loops | |
| 模式 | 重构前 | 重构后 |
|---|---|---|
| 提取方法 | 50行的函数 | 5个小型函数 |
| 提取类 | 负责5项功能的类 | 5个单一职责类 |
| 参数对象 | | |
| 替换条件判断 | | 多态 |
| 管道操作 | 嵌套循环 | |
The Rule of Three
三次原则
- First time → Just do it
- Second time → Wince and duplicate
- Third time → Refactor
- 第一次遇到 → 直接实现
- 第二次遇到 → 不情愿地重复代码
- 第三次遇到 → 进行重构
Key Patterns
核心模式
Extract Method
提取方法
javascript
// Before: Long method
function processOrder(order) {
// 50 lines of validation, calculation, saving, emailing...
}
// After: Clear responsibilities
function processOrder(order) {
validateOrder(order);
const pricing = calculatePricing(order);
const saved = saveOrder(order, pricing);
sendConfirmationEmail(saved);
return saved;
}javascript
// Before: Long method
function processOrder(order) {
// 50 lines of validation, calculation, saving, emailing...
}
// After: Clear responsibilities
function processOrder(order) {
validateOrder(order);
const pricing = calculatePricing(order);
const saved = saveOrder(order, pricing);
sendConfirmationEmail(saved);
return saved;
}Replace Loop with Pipeline
用管道操作替代循环
javascript
// Before
let results = [];
for (let item of items) {
if (item.inStock) {
results.push(item.name.toUpperCase());
}
}
// After
const results = items
.filter(item => item.inStock)
.map(item => item.name.toUpperCase());javascript
// Before
let results = [];
for (let item of items) {
if (item.inStock) {
results.push(item.name.toUpperCase());
}
}
// After
const results = items
.filter(item => item.inStock)
.map(item => item.name.toUpperCase());Decompose Conditional
分解条件判断
javascript
// Before
if (order.total > 1000 && customer.isPremium && allInStock(order)) {
return 'FREE_SHIPPING';
}
// After
function isEligibleForFreeShipping(order, customer) {
return isLargeOrder(order) &&
isPremiumCustomer(customer) &&
allInStock(order);
}javascript
// Before
if (order.total > 1000 && customer.isPremium && allInStock(order)) {
return 'FREE_SHIPPING';
}
// After
function isEligibleForFreeShipping(order, customer) {
return isLargeOrder(order) &&
isPremiumCustomer(customer) &&
allInStock(order);
}Refactoring Anti-Patterns
重构反模式
| ❌ Anti-Pattern | Problem | ✅ Better |
|---|---|---|
| Without tests | No safety net | Write tests first |
| Big bang | Rewrite everything | Small incremental steps |
| For perfection | Endless tweaking | Good enough, move on |
| Premature abstraction | Pattern not clear yet | Wait for Rule of Three |
| During feature work | Mixed changes | Separate commits |
| ❌ 反模式 | 问题 | ✅ 更好的做法 |
|---|---|---|
| 无测试重构 | 没有安全保障 | 先编写测试 |
| 大爆炸式重构 | 全盘重写 | 小步增量式修改 |
| 追求完美 | 无休止地调整 | 达到可用状态即可,继续推进 |
| 过早抽象 | 模式尚未清晰 | 遵循三次原则 |
| 与功能开发同时进行 | 变更混杂 | 分开提交 |
Agent Integration
Agent集成
typescript
// Detect code smells
const smells = await Task("Detect Code Smells", {
source: 'src/services/',
patterns: ['long-method', 'large-class', 'duplicate-code']
}, "qe-quality-analyzer");
// Safe refactoring with test verification
await Task("Verify Refactoring", {
beforeCommit: 'abc123',
afterCommit: 'def456',
expectSameBehavior: true
}, "qe-test-executor");typescript
// Detect code smells
const smells = await Task("Detect Code Smells", {
source: 'src/services/',
patterns: ['long-method', 'large-class', 'duplicate-code']
}, "qe-quality-analyzer");
// Safe refactoring with test verification
await Task("Verify Refactoring", {
beforeCommit: 'abc123',
afterCommit: 'def456',
expectSameBehavior: true
}, "qe-test-executor");Agent Coordination Hints
Agent协同提示
Memory Namespace
内存命名空间
aqe/refactoring/
├── smells/* - Detected code smells
├── suggestions/* - Refactoring recommendations
├── verifications/* - Behavior preservation checks
└── history/* - Refactoring logaqe/refactoring/
├── smells/* - Detected code smells
├── suggestions/* - Refactoring recommendations
├── verifications/* - Behavior preservation checks
└── history/* - Refactoring logFleet Coordination
集群协同
typescript
const refactoringFleet = await FleetManager.coordinate({
strategy: 'refactoring',
agents: [
'qe-quality-analyzer', // Identify targets
'qe-test-generator', // Add safety tests
'qe-test-executor', // Verify behavior
'qe-test-refactorer' // TDD refactor phase
],
topology: 'sequential'
});typescript
const refactoringFleet = await FleetManager.coordinate({
strategy: 'refactoring',
agents: [
'qe-quality-analyzer', // Identify targets
'qe-test-generator', // Add safety tests
'qe-test-executor', // Verify behavior
'qe-test-refactorer' // TDD refactor phase
],
topology: 'sequential'
});Related Skills
相关技能
- tdd-london-chicago - TDD refactor phase
- code-review-quality - Review refactored code
- xp-practices - Collective ownership
- tdd-london-chicago - TDD重构阶段
- code-review-quality - 评审重构后的代码
- xp-practices - 集体代码所有权
Remember
谨记
Refactoring is NOT:
- Adding features
- Fixing bugs
- Performance optimization
- Rewriting from scratch
Refactoring IS:
- Improving structure
- Making code clearer
- Reducing complexity
- Removing duplication
- Without changing behavior
Always have tests. Always take small steps. Always keep tests green.
重构不是:
- 添加功能
- 修复Bug
- 性能优化
- 从零重写
重构是:
- 优化结构
- 提升代码可读性
- 降低复杂度
- 消除重复代码
- 不改变代码行为
始终要有测试,始终小步推进,始终保持测试绿灯。