refactor
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseCode 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
重构流程
- Ensure tests exist - Add tests before refactoring
- Small steps - Make incremental changes
- Run tests - Verify after each change
- Commit often - Keep changes reversible
- 确保测试存在 - 重构前先添加测试
- 小步迭代 - 进行增量式修改
- 运行测试 - 每次修改后验证
- 频繁提交 - 保持修改可回滚
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
代码异味
| Smell | Symptom | Refactoring |
|---|---|---|
| Long Function | >20 lines | Extract Function |
| Large Class | >200 lines | Extract Class |
| Duplicate Code | Same logic repeated | Extract and reuse |
| Long Parameter | >3 params | Use object/builder |
| Feature Envy | Uses other class's data | Move method |
| Primitive Obsession | Strings for everything | Create 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
输入: "这个函数太长了"
操作: 识别逻辑模块,提取为专注的函数,验证测试通过
输入: "减少这些文件中的重复代码"
操作: 找出通用模式,提取共享工具函数,更新调用位置