The most important part of .NET 4.0 – code contracts

There’s been about a year since .NET 3.0 along with C# 3.0 became RTM. Clearly the most publicized feature of the release was LINQ. Is it the most widely used feature? I’d doubt so.

Simply because scope of it’s usage is limited and people have yet to learn how to use it properly. Personally the things I’m using the most often are ‘var’ and a feature I’ve been really skeptical about – automatic properties. Now, few weeks after announcements of what is going to be present in the next wave of .NET, Visual Studio and the language, the dust has settled, and we’re past initial impressions. There’s been one (well actually more than one, but I’m just going to concentrate on the one in this post) announcement, that didn’t get quite as much attention as it, in my opinion, should have.

What I’m talking is – code contracts. The reason why I think they’re so important is not, that they finally give you the tool to explicitly state your assumptions and agreements regarding behavior of your methods in a written down, commonly understood way. The reason why I think it’s important is – because Microsoft can do it.

If you think about why they tend to lock things down in the framework, producing immense number if sealed internal non-virtual and otherwise not available classes and methods, it will become clear. They do it, because by not allowing you to override, or plug-in your code, they control the implicit contract between different interacting parties. And if they control it they can verify that their implicit contract does not get violated. They lock the things so that they control who and how can call the methods and how they should behave.

With Code Contracts however, there’s no more need for that. Contracts are there to state the assumptions explicitly. They can be verified, either at compile time, or at runtime (and with ReSharper, I guess, as-you-type) and they will ensure that the assumptions methods make about their callers, are met. With that hopefully, Microsoft will acknowledge that locking things down was a poor workaround for the real problem, and since they’ll have better solution now, we’ll see more open and extensible API in the framework.

Or maybe I’m only dreaming.

Comments

ZeusTheTrueGod says:

Code Contracts may be implemented in .NET 2.0 or 3.5 with
a) Interceptors via DynamicProxy in CastleProject
b) PostSharp
c) We can writer our own CodeGenerator on Prebuild event, so each call
will start with CheckInput and ends with CheckOutput

Both can use attributes or configuration language (boo/xml)
I think that it is not so necessary for waiting new visual studio, cause we can right everything with codogenerator