共计 2255 个字符,预计需要花费 6 分钟才能阅读完成。
糟糕代码的典型特征
最近接手了一个电商优惠券系统的 Python 项目,核心逻辑不到 300 行代码却包含以下典型问题:

- 循环嵌套地狱:5 层 if-else 嵌套处理不同用户等级和优惠券类型
- 重复代码块:同样的金额校验逻辑在代码中出现 12 次
- 魔法数字 :直接使用
0.7、1000等未解释的常量值 - 超长函数:单个函数长达 200 行,包含支付、计算、校验混合逻辑
这种代码的圈复杂度达到 48(推荐值应 <10),每次修改优惠规则都像在拆炸弹。
人工重构 vs Claude 辅助效率对比
| 任务类型 | 人工耗时 | Claude 辅助 | 效率提升 |
|---|---|---|---|
| 识别坏味道 | 2 小时 | 15 分钟 | 8 倍 |
| 提取方法 | 3 小时 | 30 分钟 | 6 倍 |
| 实现工厂模式 | 6 小时 | 1 小时 | 6 倍 |
| 编写契约测试 | 4 小时 | 45 分钟 | 5.3 倍 |
分步骤重构实战
1. 使用 Claude 识别代码坏味道
将代码粘贴到 Claude 对话框并提问:
# 示例提问
请分析以下 Python 代码的质量问题,按严重程度排序:[粘贴问题代码]
Claude 会返回类似这样的分析:
1.【严重】calculate_discount()有 5 层嵌套(建议拆分为策略模式)2.【高】重复的金额校验逻辑(建议提取为 validate_amount()方法)3.【中】未处理的除零风险(第 87 行 direct_division 操作)
2. 构建优先级矩阵
使用 Claude 生成的重构优先级矩阵模板:
| 问题类型 | 影响度 | 修改难度 | ROI | 优先级 |
|----------------|-------|---------|------|-------|
| 嵌套过深 | 高 | 中 | 高 | P0 |
| 重复代码 | 中 | 低 | 高 | P1 |
| 魔法数字 | 低 | 低 | 中 | P2 |
3. 具体重构示例
Python 方法提取(前后对比)
重构前:
def process_order(user_type, coupon_type, amount):
# 重复的校验逻辑
if amount < 0:
raise ValueError("Amount cannot be negative")
if not isinstance(amount, (int, float)):
raise TypeError("Amount must be numeric")
# 业务逻辑...
if user_type == "vip":
if coupon_type == "seasonal":
return amount * 0.7
elif coupon_type == "anniversary":
return amount * 0.8
# 更多嵌套...
重构后:
def validate_amount(amount):
"""TODO: 复用此方法替换所有校验逻辑"""
if amount < 0:
raise ValueError("Amount cannot be negative")
if not isinstance(amount, (int, float)):
raise TypeError("Amount must be numeric")
return True
def calculate_vip_discount(coupon_type, amount):
"""TODO: 后续可扩展为策略模式"""
validate_amount(amount)
discounts = {
"seasonal": 0.7,
"anniversary": 0.8
}
return amount * discounts.get(coupon_type, 1.0)
Java 工厂模式示例
重构前:
public class Notification {public void send(String type, String message) {if (type.equals("email")) {// 构造 email 逻辑} else if (type.equals("sms")) {// 构造 sms 逻辑}
// 每新增类型需修改此处
}
}
重构后:
// TODO: 符合开闭原则的工厂实现
public interface Notifier {void send(String message);
}
public class NotifierFactory {public static Notifier create(String type) {switch(type) {case "email": return new EmailNotifier();
case "sms": return new SmsNotifier();
default: throw new IllegalArgumentException();}
}
}
关键配套措施
单元测试策略
- 测试覆盖率要求:重构前确保核心路径有 80%+ 覆盖率
- 契约测试技巧:
# 测试金额校验的契约 def test_validate_amount(): # 旧版本行为 assert validate_amount(100) is True assert validate_amount(-1) raises ValueError # 新版本必须保持相同行为
版本控制最佳实践
- 每个重构步骤单独提交(如 ”REFACTOR: 提取金额校验方法 ”)
- 使用
git bisect定位重构引入的问题
性能监控方案
# 使用 pyinstrument 对比重构前后
pyinstrument -r html -- open_order_page.py
进阶思考题
- 你当前项目中哪个模块的圈复杂度最高?如何用 Claude 设计拆分方案?
- 在微服务架构下,契约测试应该如何配合接口重构?
- 如何用代码变更影响分析(如 CodeQL)预测重构风险?
通过系统化应用这些方法,我们成功将示例项目的技术债减少了 67%,新功能开发速度提升 2 倍。记住:好的重构不是一次性工程,而是持续改进的日常实践。
正文完
