重构第22天 分解方法(Break Method)

时间:2023-11-28 17:44:38

理解:如果一个功能,里面比较复杂,代码量比较多,我们就可以把这个功能分解成多个小的method,每个方法实现该功能的一个小小的部分,并且方法命名成容易理解,和方法内容相关的名称,更有助于维护和可读性提高。

详解

重构前代码:

 using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text; namespace ReflectorDemo
{
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方法,因为现实中AcceptPayment方法不会做这么多的事情。,所以我们通过几次分解将 AcceptPayment拆分成若干个名字有意义且可读性更好的小方法。

重构后代码:

 using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text; namespace ReflectorDemo
{
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; }
}
}

我们把AcceptPayment的内部逻辑拆分成了CalculateSubtotal、SubtractDiscounts、AddTax、SubtractFromCustomerBalance四个功能明确且可读性更好的小方法。

这个重构和我们前面讲的“提取方法”和“提取方法对象”如出一辙,尤其是“提取方法”,所以大家只要知道用这种思想重构就行。