重构一 重新组织你的函数(Replace Temp with Query)(4)---范例

重构一 重新组织你的函数(Replace Temp with Query)(4)---范例

范例(Examples)
首先,我从一个简单函数开始:
double getPrice() {
   int basePrice = _quantity * _itemPrice;
   double discountFactor;
   if(basePrice > 1000) discountFactor = 0.95;
   else   discountFactor = 0.98;
   return basePrice * discountFactor;
}
我希望将两个临时变量都替换掉.当然,每次一个.

尽管这里的代码十分清楚,我还是先把临时变量声明为final,检查它们是否的确只被赋值一次:
double getPrice() {
   final int basePrice = _quantity * _itemPrice;
   final double discountFactor;
   if(basePrice > 1000) discountFactor = 0.95;
   else   discountFactor = 0.98;
   return basePrice * discountFactor;
}
这么一来,如果有任何问题,编译器就会警告我.之所以先做这件事,因为如果临时变量不知被赋值一次,我就不该进行这项重构.接下来我开始替换临时变量,每次一个.首先我把赋值(assignment)动作的右侧表达式提炼出来:
double getPrice() {
   final int basePrice = basePrice();
   final double discountFactor;
   if(basePrice > 1000) discountFactor = 0.95;
   else   discountFactor = 0.98;
   return basePrice * discountFactor;
}
private int basePrice() {
   return _quantity * _itemPrice;
}
编译并测试,然后开始使用Inline Temp(119).首先把临时变量basePrice的第一个引用点替换掉:
double getPrice() {
   final int basePrice = basePrice();
   final double discountFactor;
   if(basePrice() > 1000) discountFactor = 0.95;
   else   discountFactor = 0.98;
   return basePrice * discountFactor;
}

编译,测试,下一个.由于[下一个]已经是basePrice的最后一个引用点,所以我把basePrice临时变量的声明式一并摘除:
double getPrice() {
   final double discountFactor;
   if(basePrice() > 1000) discountFactor = 0.95;
   else   discountFactor = 0.98;
   return basePrice() * discountFactor;
}

搞定basePrice之后,我再以类似办法提炼出一个discountFactor():
double getPrice() {
   final double discountFactor = discountFactor();
      return basePrice() * discountFactor;
}
private double discountFactor() {
   if(basePrice() > 1000) return 0.95;
   else   return 0.98;
}

你看,如果我没有把临时变量basePrice替换为一个查询式,将多么难以提炼discountFactor()!

最终,getPrice()变成了这样:
double getPrice() {
      return basePrice() * discountFactor();
}

你可能感兴趣的:(重构一 重新组织你的函数(Replace Temp with Query)(4)---范例)