概念: 本文中的”儘快返回”是指把原來複雜的條件判斷等語句用盡快返回的方式簡化代碼。
正文:如首先聲明的是前面講的”分解複雜判斷“,簡單的來說,當你的代碼中有很深的嵌套條件時,花括號就會在代碼中形成一個長長的箭頭。我們經常在不同的代碼中看到這種情況,並且這種情況也會擾亂代碼的可讀性。下代碼所示,HasAccess方法裏面包含一些嵌套條件,如果再加一些條件或者增加複雜度,那麼代碼就很可能出現幾個問題:1,可讀性差 2,很容易出現異常 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;
}
}
}
總結: 總結:這個重構很重要,它和前面講的”分解複雜判斷“有些類似,我們在做複雜的處理過程時,要經常考慮這個重構,用好了它,會對我們的幫助很大。