This refactoring is recommended for the 10th day: the continuation of the Extraction Method
A large number of private methods and variables are extracted from a class, which will make the class bloated and hard to read.
Therefore, it is best to extract the method object to split the logic of the Function
Old Code:
Code public class OrderInfo { public decimal Price { get; private set; } } public class Order { private IList<OrderInfo> OrderLineItems { get; set; } private IList<decimal> Discounts { get; set; } private decimal Tax { get; set; } public decimal Calculate() { decimal subTotal = 0m; // Total up line items foreach (OrderInfo lineItem in OrderLineItems) { subTotal += lineItem.Price; } // Subtract Discounts foreach (decimal discount in Discounts) subTotal -= discount; // Calculate Tax decimal tax = subTotal * Tax; // Calculate GrandTotal decimal grandTotal = subTotal + tax; return grandTotal; } }
The reconstructed code passes the reference of the class that returns the calculation result to the new object that contains multiple calculation methods through the constructor method, you can also pass parameters to the constructor of the method object.
:
Code public class OrderInfo { public decimal Price { get; private set; } } public class Order { public IEnumerable<OrderInfo> OrderLineItems { get; private set; } public IEnumerable<decimal> Discounts { get; private set; } public decimal Tax { get; private set; } public decimal Calculate() { return new OrderCalculator(this).Calculate(); } } public class OrderCalculator { private decimal SubTotal { get; set; } private IEnumerable<OrderInfo> OrderLineItems { get; set; } private IEnumerable<decimal> Discounts { get; set; } private decimal Tax { get; set; } public OrderCalculator(Order order) { OrderLineItems = order.OrderLineItems; Discounts = order.Discounts; Tax = order.Tax; } public decimal Calculate() { CalculateSubTotal(); SubtractDiscounts(); CalculateTax(); return SubTotal; } private void CalculateSubTotal() { // Total up line items foreach (OrderInfo lineItem in OrderLineItems) SubTotal += lineItem.Price; } private void SubtractDiscounts() { // Subtract Discounts foreach (decimal discount in Discounts) SubTotal -= discount; } private void CalculateTax() { // Calculate Tax SubTotal += SubTotal * Tax; } }