Sep 9, 2009

Code Contracts in Visual Studio 2010

Currently still a Microsoft DevLabs Project (planned to be included in 4.0/VS2010) – Code Contracts is a very powerful tool “to sue your code”.

Definitions

Preconditions: Required state for a method to run successfully. Contract.Requires();
Postconditions: Guarantees condition that will always be true upon completion of a method. Contract.Ensures(Contract.Result<int>() != 0);
Assertions: Contract.Assert(); Contract.Assumer();
Object Invariants: guarantees about conditions that will always be true for the objects. [ContractInvariantMethod]protected void ObjectInvariant()

Code Contracts are inherited (seems correct decision according to OO substitution principle), but preconditions cannot be added, postconditions can. Interface contracts can be applied with attributes, passing a class to specifiy contract.

A basic concept is that your IL code is re-written with CC code (like it or not). Code can be statically checked or at runtime. In Visual Studio there is a new project settings tab “Code Contract”.

 

image

No comments:

Post a Comment