尽快返回就是如果方法中的条件判断可以得到结果,则尽快返回该结果。
1. 检查条件,如果不满足就立即返回,不执行下面的逻辑。
2. 当包含大量的if else嵌套,代码可读性变差,也容易出现异常。
3. 在重构时, 尽量使简单判断优先执行,尽快返回,提高性能。
代码重构前
using System.Collections.Generic; using System.Linq; using LosTechies.DaysOfRefactoring.SampleCode.BreakMethod.After; using Customer = LosTechies.DaysOfRefactoring.BreakResponsibilities.After.Customer; namespace LosTechies.DaysOfRefactoring.SampleCode.ReturnASAP.Before { public class Order { public Customer Customer { get; private set; } public decimal CalculateOrder(Customer customer, IEnumerable<Product> products, decimal discounts) { Customer = customer; decimal orderTotal = 0m; if (products.Count() > 0) { orderTotal = products.Sum(p => p.Price); if (discounts > 0) { orderTotal -= discounts; } } return orderTotal; } } }
代码重构后
using System.Collections.Generic; using System.Linq; using LosTechies.DaysOfRefactoring.SampleCode.BreakMethod.After; using Customer = LosTechies.DaysOfRefactoring.BreakResponsibilities.After.Customer; namespace LosTechies.DaysOfRefactoring.SampleCode.ReturnASAP.After { public class Order { public Customer Customer { get; private set; } public decimal CalculateOrder(Customer customer, IEnumerable<Product> products, decimal discounts) { if (products.Count() == 0) return 0; Customer = customer; decimal orderTotal = products.Sum(p => p.Price); if (discounts == 0) return orderTotal; orderTotal -= discounts; return orderTotal; } } }
代码重构后, 可读性提高,逻辑清晰。