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

重构第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     }

 

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/109076.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号