我们要介绍的重构是提取方法。这个重构极其简单但却大有裨益。首先,将逻辑置于命名良好的方法内有助于提高代码的可读性。当方法的名称可以很好地描述这部分代码的功能时,可以有效地减少其他开发者的研究时间。假设越少,代码中的bug也就越少。重构之前的代码如下:

public class Receipt {
private List<Double> Discounts;
private List<Double> ItemTotals;

public Double CalculateGrandTotal() {
Double subTotal = 0d;
for(Double itemTotal : ItemTotals) subTotal += itemTotal;
if (Discounts.size() > 0) {
for(Double discount : Discounts) subTotal -= discount;
}
Double tax = subTotal * 0.065d;
subTotal += tax;
return subTotal;
}
}
你会发现CalculateGrandTotal方法一共做了3件不同的事情:计算总额、折扣和发票税额。开发者为了搞清楚每个功能如何处理而不得不将代码从头看到尾。相比于此,向下面的代码那样将每个任务分解成单独的方法则要节省更多时间,也更具可读性:
public class Receipt {
private List<Double> Discounts;//getter setter
private List<Double> ItemTotals;//getter setter

public Double CalculateGrandTotal() {
Double subTotal = CalculateSubTotal();
subTotal = CalculateDiscounts(subTotal);
subTotal = CalculateTax(subTotal);
return subTotal;
}
private Double CalculateSubTotal() {
Double subTotal = 0d;
for(Double itemTotal : ItemTotals){
subTotal += itemTotal;
}
return subTotal;
}
private Double CalculateDiscounts(Double subTotal) {
if (Discounts.size() > 0) {
for(Double discount : Discounts){
subTotal -= discount;
}
}
return subTotal;
}
private Double CalculateTax(Double subTotal) {
Double tax = subTotal * 0.065d;
subTotal += tax;
return subTotal;
}
}





posted on 2016-08-19 09:30  jgig11  阅读(259)  评论(0编辑  收藏  举报