Tuesday, 3 March 2009

Code Contract For .NET

Developing a framework can be hard as there is alot to think about, like a user interface you need to think of the different ways it may be used and only expose those methods which make sense to be called and because most people will never read you documentation (and why should they) you make sure that each public method is named correctly. 

As we all know those framework methods form a contracts between you and the consumer as to how the framework will be used, the consumer is obliged to supply certain details and the framework is required to return certain details.

I find creating frameworks interesting, this is mainly because I have never been a great interface designer, and I also find it easier as there are a finite set of rules for how to create them, all around me in .NET I can just emulate the same structure (I see how Microsoft have done it and I copy it).

Even though the creation of frameworks removes the need to understand how to lay text boxed on a web page or form you still need to do almost as much validation, you need to make sure that the values supplied to the methods are correct, when the are not you need to throw exceptions which can be caught or the alternative is you do not worry what is supplied, but surly no one does that! 

This is how we currently validate the input and sometimes the output of our framework methods and we just hope that the code calling us also validates our data.

Like all issues us developers have come across and found a way to deal with a small team in Microsoft have said ‘we can do better’ and when it comes to the issue of method contracts (validation of data in and out) they have done exactly that with the creation of the ‘Code Contracts for .NET’.

The code contracts framework is implemented through static classes which can define pre and post conditions for any method call, you own, and once implemented the compiler will come into play to warn you of code which breaks these conditions and at runtime the exception handling processes do the same.

For me to repeat the exact details of how this work and how to implement it would be foolish so to read a better explanation by Soma (Corporate VP of Microsoft''s Developer Division) go to his blog.

Or watch the Chanel 9 video here