使用 Claude Code 进行代码重构——实战指南

使用 Claude Code 进行代码重构——实战指南

作者: CaoZH
日期: 2026-02-15
本文为原创教程


代码重构是最适合 AI 编程助手的场景之一。AI 擅长理解现有代码结构并进行系统性修改,而 Claude Code 的 Skills 系统和终端原生能力让它在重构任务中表现尤为出色。

一、准备工作

1
2
3
4
5
6
7
# 确保项目有版本控制
git init
git add .
git commit -m "chore: 重构前备份"

# 创建重构分支
git checkout -b refactor/user-service

项目上下文文件

创建 .claude/CLAUDE.md 告诉 Claude 项目规范:

1
2
3
4
5
6
7
8
9
10
11
12
# Project Context

## Tech Stack
- Spring Boot 2.7 + JDK 8
- MyBatis-Plus + MySQL
- Vue 3 + Ant Design Vue

## Code Style
- 包名: com.example.{module}
- 响应格式: { code, msg, data }
- Controller 统一用 @RestController
- Service 层必须写接口

二、重构类型与策略

1. 提取方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// 重构前:一个方法做太多事
async function createOrder(userId, items, couponCode) {
// 校验用户
const user = await db.users.findById(userId);
if (!user || user.status !== 'active') {
throw new Error('用户不存在或已禁用');
}

// 校验库存
for (const item of items) {
const product = await db.products.findById(item.productId);
if (!product || product.stock < item.quantity) {
throw new Error(`商品 ${item.productId} 库存不足`);
}
}

// 计算价格
let total = items.reduce((sum, item) => sum + item.price * item.quantity, 0);
if (couponCode) {
const coupon = await db.coupons.findByCode(couponCode);
if (coupon) total *= (1 - coupon.discount);
}

// 创建订单
const order = await db.orders.create({ userId, items, total });
return order;
}

使用 Claude Code:

1
2
claude "将这个 createOrder 方法按职责拆分为多个小方法:
validateUser、validateStock、calculatePrice、createOrderRecord"
1
2
3
4
5
6
7
// 重构后
async function createOrder(userId, items, couponCode) {
const user = await validateUser(userId);
await validateStock(items);
const total = await calculatePrice(items, couponCode);
return createOrderRecord(userId, items, total);
}

2. 提取通用工具类

1
2
claude "将项目中所有处理日期的代码提取到一个 DateUtils 工具类中,
放在 com.example.common.utils 包下"

3. 迁移到新框架

1
2
claude "将这个项目的 Spring MVC Controller 从返回 ModelAndView
迁移为 @RestController + @ResponseBody 的 RESTful 风格"

三、批量重构命令

1
2
3
4
5
6
7
8
9
10
11
# 重命名
claude /batch "将项目中所有 xxxMapper.xml 中的 namespace
从 com.old 改为 com.new"

# 统一错误处理
claude /batch "将 Controller 中的 try-catch 块
替换为使用 @ExceptionHandler 的全局异常处理"

# 添加日志
claude /batch "为所有 Service 方法的入口和出口添加日志
使用 slf4j,格式:method=xxx, params=xxx, result=xxx"

四、代码审查

重构完成后,让 Claude 进行审查:

1
2
3
4
5
claude /code-review

# 或指定范围审查
claude "审查 src/main/java/com/example/service/ 目录下的所有修改,
重点关注:1) 是否破坏了原有逻辑 2) 命名是否合理 3) 是否遗漏了边界情况"

五、验证重构

1
2
3
4
5
6
7
8
9
# 1. 运行现有测试
claude "运行所有测试,确认重构没有破坏已有功能"

# 2. 检查覆盖率
claude "检查重构后的代码测试覆盖率,标记未覆盖的分支"

# 3. 对比差异
claude "对比 refactor/user-service 和 main 分支的差异,
总结所有变更点,生成重构报告"

六、最佳实践

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
## 重构前
□ 提交当前代码(git commit)
□ 创建重构分支
□ 编写项目 CLAUDE.md
□ 识别重构范围

## 重构中
□ 分步进行,每次提交一个小改动
□ 每步都运行测试
□ 使用 /batch 处理重复性修改
□ 一次只做一种重构

## 重构后
□ 运行全部测试
□ 代码审查(/code-review)
□ 对比 diff
□ 性能测试
□ 更新文档

七、总结

1
2
3
4
5
6
# 完整重构工作流
git checkout -b refactor/module-name
claude "帮我重构这个模块..."
claude /batch "统一格式..."
claude /code-review
git commit -m "refactor: 完成模块重构"

Claude Code 特别适合的重构场景:

  • ✅ 批量重命名和迁移
  • ✅ 提取公共方法/工具类
  • ✅ 统一代码风格
  • ✅ 添加日志和异常处理
  • ✅ 框架迁移

首发于 CaoZH 的笔记