Thursday, May 14, 2009

Microsoft Contracts - The newest

Today I was reading some open source code. I saw a DLL referenced in the .NET project named "Microsoft.Contracts". I couldn't stop myself and started finding the facts about it. Hurray it is the the the latest technique developed by Microsoft which will be shipped with .NET 4.0.

The concept is based on a programming model known as Design By Contract."Design by Contract" is a method made famous by Bertrand Meyer in the Eiffel programming language where support is built right into the language constructs.

Code Contracts for .NET, is a general design-by-contract mechanism that all .NET programmers can now take advantage of. Using it, programmers provide method preconditions and postconditions. Also Contracts allow you to express object invariants in your code.

The basic idea is that a class can be viewed as having a contract with its clients whereby the class guarantees to provide certain results (postconditions of its methods) provided that the clients agree to satisfy certain requirements (preconditions of the class's methods). For example, consider a routine:
FindCustomer(int customerID)
The precondition might be that customerID is positive. The postcondition might be that we guarantee to find the customer, i.e., possibly among other things, that the return value is a non-empty string. A failure of the precondition indicates a bug in the caller, the client. A failure of the postcondition indicates a bug in the routine, the supplier.

PreConditions : These are expressed in the code using Contracts.Requires(...). PostConditions : These are expressed in the code using Contracts.Ensures(...).
Object Invariants : The Contract.Invariant() method is used to specify object invariants.

All of the contract methods are static methods de ned in the Contract class which appears in the
System.Diagnostics .Contracts namespace.

The library can be downloaded from http://research.microsoft.com/en-us/downloads/4ed7dd5f-490b-489e-8ca8-109324279968/default.aspx