• 重构第25天 引入契约设计(Introduce Design By Contract checks)


    理解:本文中的”引入契约式设计”是指我们应该对应该对输入和输出进行验证,以确保系统不会出现我们所想象不到的异常和得不到我们想要的结果。

    详解:契约式设计规定方法应该对输入和输出进行验证,这样你便可以保证你得到的数据是可以工作的,一切都是按预期进行的,如果不是按预期进行,异常或是错误就应该被返回,下面我们举的例子中,我们方法中的参数可能会值为null的情况,在这种情况下由于我们没有验证,NullReferenceException异常会报出。另外在方法的结尾处我们也没有保证会返回一个正确的decimal值给调用方法的对象。

    重构前代码:

     1  public class CashRegister
     2     {
     3         public decimal TotalOrder(IEnumerable<Product> products, Customer customer)
     4         {
     5             decimal orderTotal = products.Sum(product => product.Price);
     6 
     7             customer.Balance += orderTotal;
     8 
     9             return orderTotal;
    10         }
    11     }

    首先我们处理不会有一个null值的customer对象,检查我们最少会有一个product对象。在返回订单总和之前先确保我们会返回一个有意义的值。如果上面说的检查有任何一个失败,我们就抛出对应的异常,并在异常里说明错误的详细信息,而不是直接抛出NullReferenceException。

    重构后代码:

     1 public class CashRegister
     2     {
     3         public decimal TotalOrder(IEnumerable<Product> products, Customer customer)
     4         {
     5             if (customer == null)
     6                 throw new ArgumentNullException("customer", "Customer cannot be null");
     7             if (products.Count() == 0)
     8                 throw new ArgumentException("Must have at least one product to total", "products");
     9 
    10             decimal orderTotal = products.Sum(product => product.Price);
    11 
    12             customer.Balance += orderTotal;
    13 
    14             if (orderTotal == 0)
    15                 throw new ArgumentOutOfRangeException("orderTotal", "Order Total should not be zero");
    16 
    17             return orderTotal;
    18         }
    19     }

    上面的代码中添加了额外的代码来进行验证,虽然看起来代码复杂度增加了,但我认为这是非常值得做的,因为当NullReferenceException发生时去追查异常的详细信息真是很令人讨厌的事情。这个重构建议大家经常使用,这会增强整个系统的稳定性和健壮性。

    我们阅读微软源码的时候,会经常看到这样的代码。

  • 相关阅读:
    PHP 产生唯一码的方法分析
    Nginx 缓存cache的5种方案
    Nginx 常见应用技术指南
    BigPipe 技术细节分析
    Nginx 配置负载均衡
    linux下调整java版本
    跨域cookie在IE与firefox下的不同
    css2.1中 firefox 与IE 对margintop的不同解释
    ADOQuery代替ClientDataSet做3Tier系统
    查询数据库中的表建个进度条
  • 原文地址:https://www.cnblogs.com/yplong/p/5374050.html
Copyright © 2020-2023  润新知