概念: 本文中的”尽快返回”是指把原来复杂的条件判断等语句用尽快返回的方式简化代码。
正文:如首先声明的是前面讲的”分解复杂判断“,简单的来说,当你的代码中有很深的嵌套条件时,花括号就会在代码中形成一个长长的箭头。我们经常在不同的代码中看到这种情况,并且这种情况也会扰乱代码的可读性。下代码所示,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;
}
}
}
总结: 总结:这个重构很重要,它和前面讲的”分解复杂判断“有些类似,我们在做复杂的处理过程时,要经常考虑这个重构,用好了它,会对我们的帮助很大。