zoukankan      html  css  js  c++  java
  • 重构指南

    尽快返回就是如果方法中的条件判断可以得到结果,则尽快返回该结果。

    1. 检查条件,如果不满足就立即返回,不执行下面的逻辑。

    2. 当包含大量的if else嵌套,代码可读性变差,也容易出现异常。

    3. 在重构时, 尽量使简单判断优先执行,尽快返回,提高性能。

    代码重构前

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

    代码重构后, 可读性提高,逻辑清晰。

  • 相关阅读:
    Visual Studio 2008 每日提示(四)
    修改XP注册到用户名和公司组织名
    Visual Studio技巧之打造拥有自己标识的代码模板
    收集的学习资料
    多个记录更新(存储过程)
    '1,2,3,68,10'转换为'1,2,3,6,7,8,10'
    .NET程序员面试的题一部 (转)
    [.net]DataGrid中绑定DropDownList[转]
    使用DELETE与TRUNCATE删除表所有行的区别
    sysobjects 各列的含义
  • 原文地址:https://www.cnblogs.com/hmloo/p/6872529.html
Copyright © 2011-2022 走看看