31天重构指南之十:提取方法

现在让我们来看提取方法这个重构,这是一个简单却又好处多多的重构,首先,它通过提供有意义的方法名会使代码更具可读性;其次见名知义的方法名减少了维护人员的工作量;最后它更好的可读性减少了对代码的臆断,从而降低了代码的错误率。让我们来看下面的待重构代码:

     1: public class Receipt

   2: {
   3:     private IList<decimal> Discounts { get; set; }
   4:     private IList<decimal> 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做了三件事,首先计算了subTotal,然后减去discount,最后计算tax。与其让程序员穿越整个代码去了解CalculateGrandTotal方法的功能,
不如我们将上述三个独立的任务分配到独立方法中来提CalculateGrandTotal方法的可读性。下面是重构后的代码:
   1: public class Receipt
   2: {
   3:     private IList<decimal> Discounts { get; set; }
   4:     private IList<decimal> 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: }

这个重构来自于Martin Fowler,你可以在这里查看。

原文链接:http://www.lostechies.com/blogs/sean_chambers/archive/2009/08/10/refactoring-day-10-extract-method.aspx

你可能感兴趣的:(重构)