重构第30天 尽快返回 (Return ASAP)

理解:把条件语句中复杂的判断用尽快返回来简化。

详解如首先声明的是前面讲的”分解复杂判断“,简单的来说,当你的代码中有很深的嵌套条件时,花括号就会在代码中形成一个长长的箭头。我们经常在不同的代码中看到这种情况,并且这种情况也会扰乱代码的可读性。下代码所示,HasAccess方法里面包含一些嵌套条件,如果再加一些条件或者增加复杂度,那么代码就很可能出现几个问题:1,可读性差 2,很容易出现异常 3,性能较差

 

 1 public class Order
 2     {
 3         public Customer Customer { get; private set; }
 4 
 5         public decimal CalculateOrder(Customer customer, IEnumerable<Product> products, decimal discounts)
 6         {
 7             Customer = customer;
 8             decimal orderTotal = 0m;
 9 
10             if (products.Count() > 0)
11             {
12                 orderTotal = products.Sum(p => p.Price);
13                 if (discounts > 0)
14                 {
15                     orderTotal -= discounts;
16                 }
17             }
18 
19             return orderTotal;
20         }
21     }

那么重构上面的代码也很简单,如果有可能的话,尽量将条件判断从方法中移除,我们让代码在做处理任务之前先检查条件,如果条件不满足就尽快返回,不继续执行。下面是重构后的代码:

 1  public class Order
 2     {
 3         public Customer Customer { get; private set; }
 4 
 5         public decimal CalculateOrder(Customer customer, IEnumerable<Product> products, decimal discounts)
 6         {
 7             if (products.Count() == 0)
 8                 return 0;
 9 
10             Customer = customer;
11             decimal orderTotal = products.Sum(p => p.Price);
12 
13             if (discounts == 0)
14                 return orderTotal;
15 
16             orderTotal -= discounts;
17 
18             return orderTotal;
19         }
20     }

 

posted @ 2016-04-12 09:49  IT少年  阅读(754)  评论(0编辑  收藏  举报