Click here to Skip to main content
Click here to Skip to main content

CuttingEdge.Conditions

, 23 Jun 2011 MIT
Rate this:
Please Sign up or sign in to vote.
A pre- and postcondition validation framework based on .NET 3.5 extension methods

Introduction

CuttingEdge.Conditions is a library that helps developers to write pre- and postcondition validations in their C# 3.0 and VB.NET 9 code base. Writing these validations is easy and it improves the readability and maintainability of code.

Dependency

CuttingEdge.Conditions is language independent and can be used with both C# 3.0 and VB9. The library can be run on machines that do not have .NET 3.5 installed. While the CuttingEdge.Conditions.dll assembly itself has a dependency on System.Core (.NET 3.5), users can safely add it to their .NET 2.0 projects (as long as the C# 3.0 or VB9 compilers are used).

Conditions

Writing precondition validations raises the quality of code. Code with validations is easier to understand and allows developers to find bugs faster, mostly during development instead of during debugging. Writing precondition validations however has always been the poor relation in programming. It takes time to write it and many developers I worked with (even the ones I respect) skipped writing them.

Skipping precondition validations will lead to code that is more difficult to use and is likely to be misused. It allows developers to pass invalid method arguments, which results in unexpected program behavior and those awful NullReferenceExceptions from deep down the call stack. It leads to a higher amount of bugs and thus more time spent debugging.

The CuttingEdge.Conditions library is an attempt to lower the barrier of writing precondition validations and make code more readable, thus resulting in better code, less bugs, and shorter development cycles.

To understand how CuttingEdge.Conditions tries to achieve this, let us first have a look at some code we might write on a daily basis. Here is an C# example of precondition validations, the old fashioned way:

void TheOldFashionWay(int id, IEnumerable<int> collection, DayOfWeek day)
{
    if (id < 1)
    {
        throw new ArgumentOutOfRangeException("id", String.Format(
            "id should be greater than 0. The actual value is {0}.", id));
    }
    if (collection == null)
    {
        throw new ArgumentNullException("collection", 
            "collection should not be empty");
    }
    if (collection.Count() == 0)
    {
        throw new ArgumentException("collection should not be empty", 
            "collection");
    }
    if (day >= DayOfWeek.Monday && day <= DayOfWeek.Friday)
    {
        throw new InvalidEnumArgumentException(String.Format(
            "day should be between Monday and Friday. " +
            "The actual value is {0}.", day));
    }

    // Do method work
}

That’s an awful amount of code for a few simple validations! Here’s how it looks if CuttingEdge.Conditions would be adopted:

void TheConditionsWay(int id, IEnumerable<int> collection, DayOfWeek day)
{
    Condition.Requires(id, "id").IsGreaterThan(0);
    Condition.Requires(collection, "collection").IsNotEmpty();
    Condition.Requires(day, "day").IsInRange(DayOfWeek.Monday, DayOfWeek.Friday);

    // Do method work
} 

That’s quite different, isn't it? It’s not only far less code; it’s also very readable. And please note that both methods have exactly the same contract. Both methods throw exactly the same exceptions and exception messages!

Besides these normal precondition checks, CuttingEdge.Conditions enables you to do postcondition checks as well. Unlike a precondition, the violation of a postcondition has purely an internal cause. It can be considered a bug. Throwing an ArgumentException in that case would clearly confuse the developer using that code. Because of this difference, CuttingEdge.Conditions will always throw a PostconditionException on a violation of a postcondition.

Here is an example of a postcondition check:

public ICollection PostconditionExample()
{
    object obj = Activator.CreateInstance(typeof(Collection<int>));

    Condition.Ensures(obj, "obj").IsNotNull().IsOfType(typeof(ICollection));

    return (ICollection)obj;
} 

The postcondition example shows two interesting things. Firstly, The Ensures extension method is used to start a postcondition validation. Secondly, method calls can be chained in a fluent manner as shown with the IsNotNull and IsOfType methods.

The API

The CuttingEdge.Conditions API has many validation methods that easily cover 99% of your validation needs. There are currently 412 extension methods for 53 different checks. The API can be divided in eight groups: 

  • Entry point methods
  • Null check methods
  • Type check methods
  • Comparison checks
  • Collection checks
  • String checks
  • Numeric checks
  • Evaluations

The number of methods will possibly grow over time, and please comment here, on my blog or on CodePlex if you think there are validations missing. I will consider adding them to the library. Also note that it’s easy for you to extend the API with your own methods, by simply placing extension methods in your own project. For more information on extending CuttingEdge.Conditions, please read the Extending CuttingEdge.Conditions wiki on CodePlex.

More Information

This third stable release of the CuttingEdge.Conditions library has just been released. You can download the source and runtime library from CodePlex. Please visit conditions.codeplex.com or my blog.

Happy validating!

License

This article, along with any associated source code and files, is licensed under The MIT License

Share

About the Author

The .NET Junkie
Software Developer (Senior)
Netherlands Netherlands
I'm a freelance developer from the Netherlands, working with .NET technology on a daily basis, and officially diagnosed as a workaholic.
Follow on   Twitter

Comments and Discussions

 
GeneralRe: One more question PinmemberMr.PoorEnglish20-Jul-08 23:58 
GeneralRe: One more question PinmemberThe .NET Junkie21-Jul-08 4:38 
GeneralExtension methods on .net2.0 Pinmembergeo_m17-Jul-08 0:53 
AnswerRe: Extension methods on .net2.0 PinmemberThe .NET Junkie18-Jul-08 8:07 
Thanks for your comment.
 
I agree with you. The reason that CuttingEdge.Conditions doesn't work with older versions of the .NET framework isn't because of the extension methods. The reason it doesn't work is because it depends on types in System.Core.dll, e.g., System.Linq.Enumerable and System.Linq.Expressions.Expression).
 
As a matter of fact, you can add the CuttingEdge.Conditions assembly to your .NET 2.0 project and most of the validation methods work just fine, even if .NET 3.5 isn't installed on the machine. I believe there are currently just two methods in the API that would throw an exception when ran on a machine that hasn't got .NET 3.5 installed on it. One of them could easily be fixed (because it calls Linq.Enumerable.Contains) and the other uses an Expression<Func<T, bool>> as argument. This last one would be a problem.
 
But besides all this, I don’t know if it really makes sense to use the library with a language that doesn’t supports extension methods (like C# 2.0 and VB8). Let me give you an example. Here is some simple validation with CuttingEdge.Conditions using C# 3.0:
 
void MyMethod(IEnumerable<int> collection, object obj)
{
    collection.Requires().IsNotNull().IsLessThan(10);
    obj.Requires().IsNotNull().IsOfType(typeof(MyObject));
}
</int>
 
Using C# 2.0, it looks like this:
 
void MyMethod(IEnumerable<int> collection, object obj)
{
    Validator<IEnumerable<int>> collectionValidator = 
        ValidatorExtensions.Requires(collection);
    ValidatorExtensions.IsNotNull(collectionValidator);
    ValidatorExtensions.IsLessThan(collectionValidator, 10);
 
    Validator<object> objValidator = ValidatorExtensions.Requires(obj);
    ValidatorExtensions.IsNotNull(objValidator);
    ValidatorExtensions.IsOfType (objValidator, typeof(MyObject));
}
 
I doubt if the API is still useful when developers have to write code like this. But if you think otherwise, please let me now. I’m open to all feedback and ideas!
 
Perhaps there are even other developers who are still working on .NET 2.0 projects and love to use this library. Please let me know! We can discuss the API and if there is enough support for this, I’m willing to change it or even publish a .NET 2.0 compatible version.
 
http://www.cuttingedge.it/blogs/steven/

GeneralRe: Extension methods on .net2.0 Pinmembergeo_m21-Jul-08 0:27 
GeneralRe: Extension methods on .net2.0 PinmemberQwertie6-Aug-08 11:04 
GeneralRe: Extension methods on .net2.0 PinmemberThe .NET Junkie13-Aug-09 2:33 
GeneralGood. Here's an idea for improvement. PinmemberJudah Himango16-Jul-08 17:01 
GeneralRe: Good. Here's an idea for improvement. PinmemberThe .NET Junkie17-Jul-08 2:07 
GeneralRe: Good. Here's an idea for improvement. PinmemberJudah Himango17-Jul-08 6:13 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web02 | 2.8.141029.1 | Last Updated 23 Jun 2011
Article Copyright 2008 by The .NET Junkie
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid