简介
"用方法替换参数"是简化方法调用的重要重构技术。通过将参数计算逻辑封装为方法调用,可以降低参数传递复杂度,提高代码的内聚性和可测试性。
针对的症状(代码坏味道)
- 方法参数需要调用方进行复杂计算
- 多个调用方重复相同的参数计算逻辑
- 参数值依赖被调用对象的内部状态
- 方法签名包含业务计算逻辑参数
用方法替换参数的详细步骤
- 识别候选参数
- 查找需要前置计算的参数
- 确定参数与对象状态的关联
- 封装计算方法
- 将参数计算逻辑移至新方法
- 保持方法无副作用
- 修改方法签名
- 移除目标参数声明
- 在方法内部调用新方法
- 重构调用方
- 移除调用处的参数计算
- 保持业务逻辑不变
示例
重构前代码:
class OrderProcessor {
void process(Order order, double discountRate) {
double discount = order.getAmount() * discountRate;
order.applyDiscount(discount);
}
}
// 调用方
processor.
process(order, customer.getVIPLevel() *0.1);
重构步骤:
-
将折扣率计算封装为方法:
private double calculateDiscountRate(Customer customer) { return customer.getVIPLevel() * 0.1; } -
重构处理方法:
class OrderProcessor { void process(Order order, Customer customer) { double discountRate = calculateDiscountRate(customer); double discount = order.getAmount() * discountRate; order.applyDiscount(discount); } }
练习
基础练习题
-
简单参数替换
// 重构前 class Printer { void print(String content, boolean isLandscape) { // 打印逻辑 } }
进阶练习题
-
复合参数计算
// 重构前 class SalaryCalculator { double calculateBonus(Employee emp, double performanceScore) { return emp.getBaseSalary() * performanceScore; } }
综合拓展练习题
-
多参数方法重构
// 重构前 class ReportGenerator { void generate(List<Data> data, String format, boolean includeSummary) { // 生成报告逻辑 } }
代码审查要点
-
优点:
- 减少调用方计算负担
- 集中核心业务逻辑
- 提高方法内聚性
-
潜在问题:
- 确保方法调用成本可控
- 避免创建无状态方法
- 注意方法访问权限控制