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

时间:2022-04-23
本文章向大家介绍编写前置和后置条件的连贯接口库:CuttingEdge.Conditions,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

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

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