前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >编写前置和后置条件的连贯接口库:CuttingEdge.Conditions

编写前置和后置条件的连贯接口库:CuttingEdge.Conditions

作者头像
张善友
发布2018-01-19 16:08:36
5170
发布2018-01-19 16:08:36
举报
文章被收录于专栏:张善友的专栏张善友的专栏

当调用一个方法时,在其执行之前期望其处于特定状态; 也需要完成一些工作之后验证结果的状态。 这些假设被称为前置条件(pre-conditions )和 后置条件(post-conditions)。开源项目CuttingEdge.Conditions   是一个提供一个 fluent 接口用于指定预生成和 post-conditions的库 。 (fluent 接口是通过使用的描述性的名称和方法链的可读性会最大化一个 API 设计样式)。下面是一个用CuttingEdge.Conditions的例子:

代码语言:js
复制
public ICollection GetData(Nullable<int> id, string xml, ICollection col)   
{    
    // Check all preconditions:    
    Condition.Requires(id, "id")    
        .IsNotNull()          // throws ArgumentNullException on failure    
        .IsInRange(1, 999)    // ArgumentOutOfRangeException on failure    
        .IsNotEqualTo(128);   // throws ArgumentException on failure    
    Condition.Requires(xml, "xml")    
        .StartsWith("<data>") // throws ArgumentException on failure    
        .EndsWith("</data>"); // throws ArgumentException on failure    
    Condition.Requires(col, "col")    
        .IsNotNull()          // throws ArgumentNullException on failure    
        .IsEmpty();           // throws ArgumentException on failure    
    // Do some work 
    // Example: Call a method that should not return null   
    object result = BuildResults(xml, col);    
    // Check all postconditions:    
    Condition.Ensures(result, "result")    
        .IsOfType(typeof(ICollection)); // throws PostconditionException on failure    
    return (ICollection)result;    
}
代码语言:js
复制
 
public static int[] Multiply(int[] left, int[] right)    
{    
    Condition.Requires(left, "left").IsNotNull();    
    // You can add an optional description to each check    
    Condition.Requires(right, "right")    
        .IsNotNull()    
        .HasLength(left.Length, "left and right should have the same length");    
    // Do multiplication    
}

每个验证程序的方法调用 — IsNotNull,IsNotEmpty等 ,如果不符合该条件将引发异常。 例如空路径是否 IsNotNull 方法调用将引发一个 ArgumentNullException。  然后,可以选择提供一个字符串,用作异常消息。

不过无法在使用验证程序类中使用,这时有两种方法来做:可以验证程序类上创建扩展方法,也可以使用哪些可用于指定布尔值或 lambda 表达式计算的评估方法。 如果该表达式返回 true,处理继续 ; 如果返回 false,则引发异常。

具体的使用方法参考作者的blog:.NET Junkie's blog - Introducing CuttingEdge.Conditions 和codepoject的文章http://www.codeproject.com/KB/library/conditions.aspx

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2009-12-13 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档