31天重构学习笔记30. 尽快返回

2010-06-29 16:33  圣殿骑士  阅读(3240)  评论(6编辑  收藏  举报

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