儘快返回就是如果方法中的條件判斷可以得到結果,則儘快返回該結果。 1. 檢查條件,如果不滿足就立即返回,不執行下麵的邏輯。 2. 當包含大量的if else嵌套,代碼可讀性變差,也容易出現異常。 3. 在重構時, 儘量使簡單判斷優先執行,儘快返回,提高性能。 代碼重構前 代碼重構後 代碼重構後, 可 ...
儘快返回就是如果方法中的條件判斷可以得到結果,則儘快返回該結果。
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; } } }
代碼重構後, 可讀性提高,邏輯清晰。