IMZRH的日志

努力成为一个有用的人

导航

31天重构指南之三十:尽快返回

Posted on 2009-11-06 16:36  张荣华  阅读(403)  评论(1编辑  收藏  举报

今天要说的重构是来自于“分解复杂判断”的扩展,当应用分解复杂判断时,我们总是需要尽可能快的返回。

   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: }

原文链接:http://www.lostechies.com/blogs/sean_chambers/archive/2009/08/28/refactoring-day-30-return-asap.aspx