31 天重构学习笔记25. 引入契约式设计
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace LosTechies.DaysOfRefactoring.SampleCode.Day25_DesignByContract
{
public class CashRegister
{
public decimal TotalOrder(IEnumerable<Product> products, Customer customer)
{
decimal orderTotal = products.Sum(product => product.Price);
customer.Balance += orderTotal;
return orderTotal;
}
}
}
对上面的代码重构是很简单的,首先我们处理不会有一个null值的customer对象,检查我们最少会有一个product对象。在返回订单总和之前先确保
我们会返回一个有意义的值。如果上面说的检查有任何一个失败,我们就抛出对应的异常,并在异常里说明错误的详细信息,而不是直接抛出NullReferenceException。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Contracts;
namespace LosTechies.DaysOfRefactoring.SampleCode.DesignByContract.After
{
public class CashRegister
{
public decimal TotalOrder(IEnumerable<Product> products, Customer customer)
{
if (customer == null)
throw new ArgumentNullException("customer", "Customer cannot be null");
if (products.Count() == 0)
throw new ArgumentException("Must have at least one product to total", "products");
decimal orderTotal = products.Sum(product => product.Price);
customer.Balance += orderTotal;
if (orderTotal == 0)
throw new ArgumentOutOfRangeException("orderTotal", "Order Total should not be zero");
return orderTotal;
}
}
}
上面的代码中添加了额外的代码来进行验证,虽然看起来代码复杂度增加了,但我认为这是非常值得做的,因为当NullReferenceException发生时去追查异常的详细信息
真是很令人讨厌的事情。
总结:微软在处理代码乃至产品的时候,很喜欢应用此重构,你如果认真看它的代码库,认真看一下WCF的设计,就不难发现了。这个重构建议大家经常使用,
这会增强整个系统的稳定性和健壮性。
本文转自KnightsWarrior51CTO博客,原文链接:http://blog.51cto.com/knightswarrior/342482 ,如需转载请自行联系原作者