When a method is called, it is expected to be in a specific State before it is executed; it also needs to verify the result state after some work is completed. These assumptions are called pre-conditions and post-conditions ). The open-source project cuttingedge. conditions is a library that provides a fluent interface to specify pre-generation and post-conditions. (The fluent interface maximizes the readability of an API design style by using descriptive names and method chains ). The following is an example of using cuttingedge. conditions:
Public icollection getdata (nullable <int> ID, string XML, icollection col)
{
// Check all preconditions:
Condition. Requires (ID, "ID ")
. Isnotnull () // throws argumentnullexception on Failure
. Isinscope (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 shocould 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 shocould have the same length ");
// Do multiplication
}
Method call of each validators-isnotnull, isnotempty, etc. If this condition is not met, an exception is thrown. For example, if the empty path is called by the isnotnull method, an argumentnullexception is triggered. Then, you can choose to provide a string for exception messages.
But it cannot be used in the use of the validators class. There are two ways to do this: you can create extension methods on the validators class, which evaluation methods can be used to specify boolean values or lambda expressions. If this expression returns true, processing continues. If false is returned, an exception is thrown.
For detailed usage, refer to the author's blog:. Net junkie's blog-introducing cuttingedge. Conditions and codepoject Article http://www.codeproject.com/KB/library/conditions.aspx.