概念:本文中的把某些计算复杂的过程按照功能提取成各个小方法,这样就可以使代码的可读性、维护性得到提高。
正文:如下代码所示,CalculateGrandTotal方法里面包含了多个逻辑,第一计算subTotal 的总和,第二subTotal 要循环减去discount,也就是计算Discounts,第三就是计算Tax。所以我们可以根据功能把他们拆分成三个小方法。
using System.Collections.Generic; namespace LosTechies.DaysOfRefactoring.ExtractMethod.Before { 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方法就直接调用CalculateSubTotal、CalculateDiscounts、CalculateTax,从而是整个逻辑看起来更加清晰,并且可读性和维护性也得到了大大提高。
using System.Collections.Generic; namespace LosTechies.DaysOfRefactoring.ExtractMethod.After { 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; } } }
总结:这个重构在很多公司都有一些的代码规范作为参考,比如一个类不能超过多少行代码,一个方法里面不能超过多少行代码,这在一定程度上也能使程序员把这些复杂的逻辑剥离成意义很清楚的小方法。