重构25-Introduce Design By Contract checks(契约式设计)
2016-08-19 09:45
465 查看
契约式设计(DBC,Design By Contract)定义了方法应该包含输入和输出验证。因此,可以确保所有的工作都是基于可用的数据,并且所有的行为都是可预料的。否则,将返回异常或错误并在方法中进行处理。要了解更多关于DBC的内容,可以访问wikipedia。 在我们的示例中,输入参数很可能为null。由于没有进行验证,该方法最终会抛出NullReferenceException。在方法最后,我们也并不确定是否为用户返回了一个有效的Double,这可能导致在别的地方引入其他方法。
来自为知笔记(Wiz)
public class CashRegister { public Double TotalOrder(List<Product> products, Customer customer) { Double orderTotal =sum(products); customer.Balance += orderTotal; return orderTotal; } Double sum(List<Product> products){ Double sum=0d; for(Product p:List<Product>){ sum+=p.Price; } return sum; } }在此处引入DBC验证是十分简单的。首先,我们要声明customer不能为null,并且在计算总值时至少要有一个product。在返回订单总值时,我们要确定其值是否有效。如果此例中任何一个验证失败,我们将以友好的方式抛出相应的异常来描述具体信息,而不是抛出一个晦涩的NullPointException。
public class CashRegister { public Double TotalOrder(List<Product> products, Customer customer) { if (customer == null) throw new IllegalArgumentException("customer Customer cannot be null"); if (products.size() == 0) throw new IllegalArgumentException("Must have at least one product to total products"); Double orderTotal = sum(products); customer.Balance += orderTotal; if (orderTotal == 0) throw new ArrayIndexOutOfBoundsException("orderTotal Order Total should not be zero"); return orderTotal; } Double sum(List<Product> products){ Double sum=0d; for(Product p:List<Product>){ sum+=p.Price; } return sum; } }在验证过程中确实增加了不少代码,你也许会认为过度使用了DBC。但我认为在大多数情况下,处理这些棘手的问题所做的努力都是值得的。追踪无详细内容的IllegalArgumentException的确不是什么美差。
来自为知笔记(Wiz)
相关文章推荐
- 重构第25天 引入契约设计(Introduce Design By Contract checks)
- Design by Contract 契约式设计
- 软件设计方法--契约式设计Design by contract
- 译文:Design by Contract(契约式设计)
- Design by Contract (DBC) 契约式设计
- Design By Contract 契约式设计
- Design by Contract(契约式设计)
- Design By Contract 契约式设计
- Design By Contract(契约式设计)
- 契约式设计 Design by contract
- 31天重构学习笔记25. 引入契约式设计
- 31天重构学习笔记25. 引入契约式设计
- 31天重构学习笔记25. 引入契约式设计
- .NET 4.0中的新功能介绍:契约式设计 (Design By Contracts)
- .NET 4.0中的新功能介绍:契约式设计 (Design By Contracts)
- 软件的按契约设计(DbC---Design by Contract)
- NET 4.0中的新功能介绍:契约式设计 (Design By Contracts)
- Design By Contract 基于契约设计的个人理解
- C#中如何使用----按合约设计(Design by Contract)
- 31天重构学习笔记25. 引入契约式设计