这一条重构的建议是尽量提取方法,使得代码更加清晰明了

旧的代码:

    public class Receipt
     {
        private IList<decimal> Discounts { get; set; }
        private IList<decimal> ItemTotals { get; set; }
        public decimal CalculateGrandTotal()
         {
            decimal subTotal = 0m;
            foreach (decimal itemTotal in ItemTotals)
                 subTotal += itemTotal;
            if (Discounts.Count > 0)
             {
                foreach (decimal discount in Discounts)
                     subTotal -= discount;
             }
            decimal tax = subTotal * 0.065m;
             subTotal += tax;
            return subTotal;
         }
     }

为了弄明白CalculateGrandTotal() 这个方法的意思你会把代码整个看一遍,从而知道是做了3件事情

1,计算总额

2,计算优惠折扣

3,添加消费税

相比较而言我们可以作如下重构

    public class Receipt
     {
        private IList<decimal> Discounts { get; set; }
        private IList<decimal> ItemTotals { get; set; }
        public decimal CalculateGrandTotal()
         {
            decimal subTotal = CalculateSubTotal();
             subTotal = CalculateDiscounts(subTotal);
             subTotal = CalculateTax(subTotal);
            return subTotal;
         }
        private decimal CalculateTax(decimal subTotal)
         {
            decimal tax = subTotal * 0.065m;
             subTotal += tax;
            return subTotal;
         }
        private decimal CalculateDiscounts(decimal subTotal)
         {
            if (Discounts.Count > 0)
             {
                foreach (decimal discount in Discounts)
                     subTotal -= discount;
             }
            return subTotal;
         }
        private decimal CalculateSubTotal()
         {
            decimal subTotal = 0m;
            foreach (decimal itemTotal in ItemTotals)
                 subTotal += itemTotal;
            return subTotal;
         }
     }

将三件事情分成三个子方法,这样每个方法可以专司其职,使得代码更具有可读性

这是一个很重要的重构方法,方法尽量不要超过100行,因为越长的方法越容易出bug


Leave a Reply