理解:经常写的代码中,有一些计算逻辑比较复杂的方法,写下来一个很长很长的方法,我们可以把这个方法,根据功能,分解成单独的几个小方法。这样做不仅能够增加代码的可维护性,而且增加了易读性。
详解:
重构前代码:
1 public class Receipt 2 { 3 private IListDiscounts { get; set; } 4 private IList ItemTotals { get; set; } 5 6 public decimal CalculateGrandTotal() 7 { 8 decimal subTotal = 0m; 9 foreach (decimal itemTotal in ItemTotals)10 subTotal += itemTotal;11 12 if (Discounts.Count > 0)13 {14 foreach (decimal discount in Discounts)15 subTotal -= discount;16 }17 18 decimal tax = subTotal * 0.065m;19 20 subTotal += tax;21 22 return subTotal;23 }24 }
我们看到CalculateGrandTotal方法,里面用到了2个foreach循环,看一下,还真不宜理解,不晓得每个foreach主要做什么。
看看重构后的代码:
1 public class Receipt 2 { 3 private IListDiscounts { get; set; } 4 private IList ItemTotals { get; set; } 5 6 public decimal CalculateGrandTotal() 7 { 8 decimal subTotal = CalculateSubTotal(); 9 10 subTotal = CalculateDiscounts(subTotal);11 12 subTotal = CalculateTax(subTotal);13 14 return subTotal;15 }16 17 private decimal CalculateTax(decimal subTotal)18 {19 decimal tax = subTotal * 0.065m;20 21 subTotal += tax;22 return subTotal;23 }24 25 private decimal CalculateDiscounts(decimal subTotal)26 {27 if (Discounts.Count > 0)28 {29 foreach (decimal discount in Discounts)30 subTotal -= discount;31 }32 return subTotal;33 }34 35 private decimal CalculateSubTotal()36 {37 decimal subTotal = 0m;38 foreach (decimal itemTotal in ItemTotals)39 subTotal += itemTotal;40 return subTotal;41 }42 }
重构后,我们把CalculateGrandTotal方法分解成3个小方法,每个方法名称根据其功能命名。CalculateTax顾名思义,就是计算税收,CalculateDiscounts就是计算折扣金额。
这样就把逻辑剥离的很清楚了。