refactoring-patterns

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Refactoring Patterns

重构模式

<default_to_action> When refactoring:
  1. ENSURE tests pass (never refactor without tests)
  2. MAKE small change (one refactoring at a time)
  3. RUN tests (must stay green)
  4. COMMIT (save progress)
  5. REPEAT
Safe Refactoring Cycle:
bash
npm test               # Green ✅
<default_to_action> 进行重构时:
  1. 确保测试通过(绝不要在没有测试的情况下重构)
  2. 做出微小改动(一次只进行一项重构)
  3. 运行测试(必须保持绿灯状态)
  4. 提交(保存进度)
  5. 重复
安全重构循环:
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

常见重构方式

PatternBeforeAfter
Extract Method50-line function5 small functions
Extract ClassClass doing 5 things5 single-purpose classes
Parameter Object
fn(a,b,c,d,e,f)
fn(options)
Replace Conditional
if (type === 'a') {...}
Polymorphism
PipelineNested loops
.filter().map().reduce()
模式重构前重构后
提取方法50行的函数5个小型函数
提取类负责5项功能的类5个单一职责类
参数对象
fn(a,b,c,d,e,f)
fn(options)
替换条件判断
if (type === 'a') {...}
多态
管道操作嵌套循环
.filter().map().reduce()

The Rule of Three

三次原则

  1. First time → Just do it
  2. Second time → Wince and duplicate
  3. Third time → Refactor

  1. 第一次遇到 → 直接实现
  2. 第二次遇到 → 不情愿地重复代码
  3. 第三次遇到 → 进行重构

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-PatternProblem✅ Better
Without testsNo safety netWrite tests first
Big bangRewrite everythingSmall incremental steps
For perfectionEndless tweakingGood enough, move on
Premature abstractionPattern not clear yetWait for Rule of Three
During feature workMixed changesSeparate 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 log
aqe/refactoring/
├── smells/*          - Detected code smells
├── suggestions/*     - Refactoring recommendations
├── verifications/*   - Behavior preservation checks
└── history/*         - Refactoring log

Fleet 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
  • 性能优化
  • 从零重写
重构是:
  • 优化结构
  • 提升代码可读性
  • 降低复杂度
  • 消除重复代码
  • 不改变代码行为
始终要有测试,始终小步推进,始终保持测试绿灯。