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

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

  • 相关阅读:
    3.nginx反向代理服务器+负载均衡
    2.nginx整合PHP
    nginx-location rewrite
    Nginx(一):安装
    修改host文件原理 localhost,127.0.0.1之间有什么区别
    一个IP绑定多个域名
    私有IP
    转:Hadoop和Spark的异同
    C#中Trim()、TrimStart()、TrimEnd()的用法
    Java操作redis
  • 原文地址:https://www.cnblogs.com/hmloo/p/6872529.html
Copyright © 2011-2022 走看看