以函数取代参数
对象调用某个函数,并将所得结果作为参数,传递给另一个函数。
动机
如果函数可以通过其他途径(而非参数列)获得参数值,那么它就不应该通过参数获得该值,过长的参数会增加阅读难道。
看看参数接收端是否可以通过与调用端相同的计算来取得参数携带值
- 通过所属对象内部的另一个函数来计算参数,可以将这个计算过程转移到调用端内,从而去掉参数。
- 调用的函数隶属另也给对象,让该对象拥有一个reference指向调用端所属对象。
- 如果参数计算过程依赖调用端某个参数,那么就无法去掉被调用端的那个函数。
作法
- 如果有必要,将参数的计算过程提炼到一个独立函数中。
- 将函数本体内对该参数的引用替换为对新建函数的调用。
- 每次替换后,修改并测试。
- 全部替换完成后,使用remove parameter将该参数去掉。
范例
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 discountLevel) {
if (discountLevel == 2) return basePrice * 0.1;
else return basePrice * 0.05;
}
=================>
// 抽象计算折扣等级代码
private int getDiscountLevel(){
if (_quantity > 100) return 2;
else return 1;
}
public double getPrice(){
int basePrice = _quantity * _itemPrice;
int discountLevel = getDiscountLevel();
return discountedPrice(basePrice, discountLevel);
}
...
=================>
...
// 把discountedPrice() 函数中对discountLevel 参数的所有引用点, 替换为getDiscountLevel() 函数的调用
// Remove Parameter 去掉discountLevel参数
private discountedPrice(int basePrice) {
if (getDiscountLevel() == 2) return basePrice * 0.1;
else return basePrice * 0.05;
}
...
private int getBasePrice() {
return _quantity * _itemPrice;
}
// 针对discountedPrice使用inline Method
private double getPrice(){
if (getDiscountLevel() == 2) return getBasePrice() * 0.1;
else return getBasePrice() * 0.05;
}