refactor

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Code Refactoring

代码重构

Improve code quality without changing behavior.
在不改变代码行为的前提下提升代码质量。

When to Use

适用场景

  • Code is hard to understand or modify
  • Duplicated logic across files
  • Functions/classes are too large
  • Technical debt reduction
  • Before adding new features
  • 代码难以理解或修改
  • 多个文件中存在重复逻辑
  • 函数/类过于庞大
  • 需要减少技术债务
  • 添加新功能之前

Refactoring Process

重构流程

  1. Ensure tests exist - Add tests before refactoring
  2. Small steps - Make incremental changes
  3. Run tests - Verify after each change
  4. Commit often - Keep changes reversible
  1. 确保测试存在 - 重构前先添加测试
  2. 小步迭代 - 进行增量式修改
  3. 运行测试 - 每次修改后验证
  4. 频繁提交 - 保持修改可回滚

Common Refactorings

常见重构手法

Extract Function

提取函数

javascript
// Before
function processOrder(order) {
  // 50 lines of validation
  // 30 lines of calculation
  // 20 lines of notification
}

// After
function processOrder(order) {
  validateOrder(order);
  const total = calculateTotal(order);
  notifyCustomer(order, total);
}
javascript
// Before
function processOrder(order) {
  // 50 lines of validation
  // 30 lines of calculation
  // 20 lines of notification
}

// After
function processOrder(order) {
  validateOrder(order);
  const total = calculateTotal(order);
  notifyCustomer(order, total);
}

Replace Conditionals with Polymorphism

用多态替换条件语句

javascript
// Before
function getPrice(type) {
  if (type === "regular") return basePrice;
  if (type === "premium") return basePrice * 1.5;
  if (type === "vip") return basePrice * 0.8;
}

// After
const pricingStrategies = {
  regular: (base) => base,
  premium: (base) => base * 1.5,
  vip: (base) => base * 0.8,
};
const getPrice = (type) => pricingStrategies[type](basePrice);
javascript
// Before
function getPrice(type) {
  if (type === "regular") return basePrice;
  if (type === "premium") return basePrice * 1.5;
  if (type === "vip") return basePrice * 0.8;
}

// After
const pricingStrategies = {
  regular: (base) => base,
  premium: (base) => base * 1.5,
  vip: (base) => base * 0.8,
};
const getPrice = (type) => pricingStrategies[type](basePrice);

Remove Duplication

移除重复代码

javascript
// Before
function getUserName(user) {
  return user?.profile?.name ?? "Unknown";
}
function getOrderName(order) {
  return order?.customer?.name ?? "Unknown";
}

// After
const getName = (obj, path) => path.reduce((o, k) => o?.[k], obj) ?? "Unknown";
const getUserName = (user) => getName(user, ["profile", "name"]);
const getOrderName = (order) => getName(order, ["customer", "name"]);
javascript
// Before
function getUserName(user) {
  return user?.profile?.name ?? "Unknown";
}
function getOrderName(order) {
  return order?.customer?.name ?? "Unknown";
}

// After
const getName = (obj, path) => path.reduce((o, k) => o?.[k], obj) ?? "Unknown";
const getUserName = (user) => getName(user, ["profile", "name"]);
const getOrderName = (order) => getName(order, ["customer", "name"]);

Code Smells

代码异味

SmellSymptomRefactoring
Long Function>20 linesExtract Function
Large Class>200 linesExtract Class
Duplicate CodeSame logic repeatedExtract and reuse
Long Parameter>3 paramsUse object/builder
Feature EnvyUses other class's dataMove method
Primitive ObsessionStrings for everythingCreate value objects
异味类型表现特征重构手法
过长函数超过20行提取函数
过大类超过200行提取类
重复代码相同逻辑重复出现提取并复用
参数过多超过3个参数使用对象/构建器
特性依恋过度依赖其他类的数据移动方法
基本类型偏执所有数据都用字符串表示创建值对象

Quality Metrics

质量指标

  • Cyclomatic Complexity - Keep under 10 per function
  • Nesting Depth - Max 3 levels
  • Function Length - Under 20 lines preferred
  • File Length - Under 300 lines preferred
  • 圈复杂度 - 每个函数保持在10以下
  • 嵌套深度 - 最多3层
  • 函数长度 - 建议不超过20行
  • 文件长度 - 建议不超过300行

Safety Checklist

安全检查清单

  • Tests exist and pass
  • No behavior changes intended
  • Changes are incremental
  • Each step is committed
  • Code review requested
  • 测试已存在且全部通过
  • 无意改变代码行为
  • 修改为增量式进行
  • 每一步修改都已提交
  • 已请求代码评审

Examples

示例

Input: "This function is too long" Action: Identify logical sections, extract into focused functions, verify tests pass
Input: "Reduce duplication in these files" Action: Find common patterns, extract shared utilities, update call sites
输入: "这个函数太长了" 操作: 识别逻辑模块,提取为专注的函数,验证测试通过
输入: "减少这些文件中的重复代码" 操作: 找出通用模式,提取共享工具函数,更新调用位置