过多的入参
- 含义:
一个函数(方法)的入参太多 - 坏处:
可读性差,不易使用。 - 目标:
使入参统一,易读,易用,并注意不造成过多耦合。 - 实现方法:
- 如果某个方法已经可以获取这个方法的某(几)个入参,把这个入参去掉,直接在这个方法里调用可以获取到这个入参的方法,考虑使用Replace Parameter with Method (以函数取代入参)。
- 如果某一些入参正好同属于一个对象的属性,考虑使用Preserve Whole Object (保持对象完整)
- 如果某些入参经常一起出现,考虑使用Introduce Parameter Object (引入入参对象)。
本文涉及的重构方法
Replace Parameter with Method (以函数取代入参)
- 把代码逻辑中,某些计算过程提炼到一个独立的函数(方法)中
- 把使用该参数作为入参的函数,去掉该入参,改为直接在这个函数内调用这个独立函数。
- 编译,测试。
//参考官方例子
//重构前
//带下划线的变量是假设该变量已经存在
//此方法根据物品单价和数量计算折扣,最后得出总价
public double getPrice() {
int basePrice = _quantity * _itemPrice;
int discountLevel;
if(_quantity > 100) discountLevel = 2;
else discountLevel = 1;
double finalPrice = discountedPrice(basePrice, discountLevel);
return finalPrice;
}
private double discountedPrice(int basePrice, int discountedLevel) {
if( discountLevel == 2) return basePrice * 0.1;
else return basePrice * 0.05;
}
//重构后
public double getPrice() {
return discountedPrice();
}
private double discountedPrice() {
if (getDiscountedLevel() == 2) return getBasePrice() * 0.1;
else return getBasePrice() * 0.05;
}
private double getBasePrice() {
return _quantity * _itemPrice;
}
private int getDiscountedLevel() {
if(_quantity > 100) return 2;
else return 1;
}
- 重构思路:
代码中通过某些计算得出来的变量,作为入参传入另一个函数的时候,考虑是否可以把这个计算过程独立成一个函数,然后消除该入参,改为直接在调用的那个函数中使用这个独立函数,这样可以使入参更少,代码结构更清晰。 - 建议:
此方法增加了许多新方法,还有原来的入参也需要处理,酌情使用。本质上是为了减少不必要的入参,提升可读性。