关于 refactor
面向代码维护的重构技能,指导开发者在不改变行为的前提下改善代码结构。内容包括常见重构方法、代码异味和逐步验证流程。
主要功能
- 01提取函数与类
- 02替换条件逻辑
- 03识别并消除重复
- 04检查代码异味
- 05以测试验证渐进改动
- 06提供复杂度与长度指标
适用场景
- 01拆分难以理解的长函数
- 02整理多个文件中的重复逻辑
- 03在新增功能前降低技术债
- 04通过小步修改改善代码结构
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ htlin222/ dotfiles --skill refactor安装后在 Claude Code 中输入/refactor确认已加载。
详细介绍
代码重构
在不改变行为的前提下提升代码质量。
适用场景
- 代码难以理解或修改
- 多个文件中存在重复逻辑
- 函数或类过大
- 减少技术债务
- 添加新功能之前
重构流程
- 确保存在测试 - 重构前添加测试
- 小步进行 - 逐步修改
- 运行测试 - 每次修改后验证
- 经常提交 - 确保更改可撤销
常见重构方式
提取函数
// 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);
}
用多态替换条件判断
// 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);
消除重复
// 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"]);
代码异味
| 异味 | 症状 | 重构方式 |
|---|---|---|
| 函数过长 | 超过 20 行 | 提取函数 |
| 类过大 | 超过 200 行 | 提取类 |
| 代码重复 | 重复相同逻辑 | 提取并复用 |
| 参数过多 | 超过 3 个参数 | 使用对象或构建器 |
| 过度依赖其他类 | 使用其他类的数据 | 移动方法 |
| 基本类型偏执 | 所有内容都用字符串表示 | 创建值对象 |
质量指标
- 圈复杂度 - 每个函数保持在 10 以下
- 嵌套深度 - 最多 3 层
- 函数长度 - 建议少于 20 行
- 文件长度 - 建议少于 300 行
安全检查清单
- 测试存在且通过
- 不打算改变行为
- 更改是渐进式的
- 每个步骤都已提交
- 已请求代码审查
示例
输入:“这个函数太长了” **操作:**找出逻辑部分,将其提取为职责明确的函数,并验证测试通过
输入:“减少这些文件中的重复代码” **操作:**找出共同模式,提取共享工具,并更新调用位置
评论
支持 Markdown