概念:本文中的”分解方法”是指把我们所做的这个功能不停的分解方法,直到将一个大方法分解为名字有意义且可读性更好的若干个小方法。
正文:如下代码所示,因为现实中AcceptPayment方法不会做这么多的事情。,所以我们通过几次分解将 AcceptPayment拆分成若干个名字有意义且可读性更好的小方法。
using System.Collections.Generic;
using System.Linq;
namespace LosTechies.DaysOfRefactoring.SampleCode.BreakMethod.Before
{
public class CashRegister
{
public CashRegister()
{
Tax = 0.06m;
}
private decimal Tax { get; set; }
public void AcceptPayment(Customer customer, IEnumerable<Product> products, decimal payment)
{
decimal subTotal = 0m;
foreach (Product product in products)
{
subTotal += product.Price;
}
foreach (Product product in products)
{
subTotal -= product.AvailableDiscounts;
}
decimal grandTotal = subTotal * Tax;
customer.DeductFromAccountBalance(grandTotal);
}
}
public class Customer
{
public void DeductFromAccountBalance(decimal amount)
{
// deduct from balance
}
}
public class Product
{
public decimal Price { get; set; }
public decimal AvailableDiscounts { get; set; }
}
}
重构后的代码如下,我们把AcceptPayment的内部逻辑拆分成了CalculateSubtotal、SubtractDiscounts、AddTax、SubtractFromCustomerBalance四个功能明确且可读性更好的小方法。
using System.Collections.Generic;
namespace LosTechies.DaysOfRefactoring.SampleCode.BreakMethod.After
{
public class CashRegister
{
public CashRegister()
{
Tax = 0.06m;
}
private decimal Tax { get; set; }
private IEnumerable<Product> Products { get; set; }
public void AcceptPayment(Customer customer, IEnumerable<Product> products, decimal payment)
{
decimal subTotal = CalculateSubtotal();
subTotal = SubtractDiscounts(subTotal);
decimal grandTotal = AddTax(subTotal);
SubtractFromCustomerBalance(customer, grandTotal);
}
private void SubtractFromCustomerBalance(Customer customer, decimal grandTotal)
{
customer.DeductFromAccountBalance(grandTotal);
}
private decimal AddTax(decimal subTotal)
{
return subTotal * Tax;
}
private decimal SubtractDiscounts(decimal subTotal)
{
foreach (Product product in Products)
{
subTotal -= product.AvailableDiscounts;
}
return subTotal;
}
private decimal CalculateSubtotal()
{
decimal subTotal = 0m;
foreach (Product product in Products)
{
subTotal += product.Price;
}
return subTotal;
}
}
public class Customer
{
public void DeductFromAccountBalance(decimal amount)
{
// deduct from balance
}
}
public class Product
{
public decimal Price { get; set; }
public decimal AvailableDiscounts { get; set; }
}
}
总结:其实这个重构和我们前面讲的“提取方法”和“提取方法对象”如出一辙,尤其是“提取方法”,所以大家只要知道用这种思想重构就行。