Code Contracts
On Monday, Microsoft released a preview version of Code Contracts, the design-by-contract feature that will be included in the .NET 4.0 Base Class Library. This appears to have been born out of the Spec# research project, but is available for all .NET languages, rather than being an extension of C#.
I’ve just been having a quick play, and it really is quite sweet, particularly the static code analysis that detects contract violations before the program is executed.
For example, here’s part of a repository class I wrote a few years ago, to return a collection of customers matching criteria defined in a query object. In time-honoured tradition, I validated the input parameters to my public method with guard-clauses, and threw exceptions as appropriate at runtime:
/// <summary>
/// Search for a collection of customers, given a set of criteria.
/// </summary>
/// <param name="queryCriteria" />Query Object defining the search criteria.</param>
/// <returns>Collection of customers matching the specified criteria.</returns>
/// <exception cref="System.ArgumentNullException">Where queryCriteria is null</exception>
/// <exception cref="System.ArgumentException">Where no query criteria have been set (we do not permit searching for all customers)</exception>
public static CustomerCollection Find(CustomerQuery queryCriteria)
{
#region Validate parameters
// Guard clause 1 - null queryCriteria - throw exception
if ( queryCriteria == null ) throw new ArgumentNullException( "queryCriteria" );
// Guard clause 2 - no query criteria specified - throw exception
if ( !queryCriteria.IsUsed( SourceSystem.All ) ) throw new ArgumentException( ExceptionMessages.BusinessLogic_CustomerRepository_Find_NoCriteriaSpecified, "queryCriteria" );
#endregion
// More stuff here to return customers
}
Now, in this brave new world of design-by-contract, we can rewrite those guard clauses more expressively as:
// Guard clause 1 - null queryCriteria Contract.Requires( queryCriteria!=null ); // Guard clause 2 - no query criteria specified Contract.Requires( queryCriteria.IsUsed( SourceSystem.All ), ExceptionMessages.BusinessLogic_CustomerRepository_Find_NoCriteriaSpecified);
And, having enabled the static analysis and squiggly line options (via a new project properties pane), we get design-time warnings of contract violations:
I also like the way that automated testing tools such as Pex can make use of the contracts to generate more meaningful unit tests. Yet more grunt work we can offload onto the IDE
There’s much more to it than this, and I encourage you to take a look at the site, and browse the documentation. It strikes me as being an excellent tool to help build bullet-proof class libraries, and I look forward to using it in earnest in .NET 4.0.








