• 重构指南


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

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

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

  • 相关阅读:
    mongodb 配置单实例与双实例
    redis 集群 搭建
    memcached 搭建
    公网yum 源地址
    jdk 安装
    activemq 搭建--集群
    zookeeper 安装
    activemq 安装-单点
    rabbitmq 集群
    python——网络编程
  • 原文地址:https://www.cnblogs.com/hmloo/p/6872529.html
Copyright © 2020-2023  润新知