Code Contracts is the .NET implementation of the Design by Contract concept. While it was supposed to be delivered with .NET 4.0, Code Contracts is already available for download from DevLabs. Contracts impose certain restrictions on using APIs, making programming safer, having more validations and resulting in fewer unexpected errors during runtime.
Design by Contract, or Programming by Contract, is not a new concept in programming, many languages already having such implementations. Code Contract brings this programming paradigm to .NET. The basic idea is to establish a contract between the two parties involved: the client (caller) and the supplier (API called). By adhering to the terms of the contract, the client is more confident the supplier will supply expected results, and the supplier will be more confident that the client will make appropriate calls.
There are three types of contract conditions available for Code Contracts: pre-conditions, object invariants, and post-conditions. Pre-conditions are used, for example, to verify that a constructor or a method is called using the right parameter values. A post-condition is used to verify that a value returned is appropriate. Object invariants are used to enforce certain conditions on objects to make sure they don’t obtain illegal values.
While this sounds very similar to unit testing, what’s news is that those validations can be performed at build time. The compiler will make specific checks via Contracts to ensure that all the conditions specified are met, issuing warning if they are not. The programmer can immediately see if a condition is not going to be met and take corrective measures before running the code.
Currently, the DevLabs team works on including Contracts in the documentation generated for projects. By reading an API documentation, anyone will be able to see all the contract conditions specified for it.
The end result of using Code Contracts is better and safer code, more appropriate usage of external APIs, in the end better software.
Useful links: Code Contracts online documentation, Microsoft Research Code Contracts website, related forum.