一天一个重构方法(17):尽早返回
2009-07-02 19:23:29Return ASAP:尽早返回
该话题实际上是诞生于移除箭头反模式重构之中。在移除箭头时,它被认为是重构产生的副作用。为了消除箭头,你需要尽快地return。
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;
}
}
该重构的理念就是,当你知道应该处理什么并且拥有全部需要的信息之后,立即退出所在方法,不再继续执行。
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)
return 0m;
orderTotal = products.Sum(p => p.Price);
if (discounts <= 0)
return orderTotal;
orderTotal -= discounts;
return orderTotal;
}
}