Justin du Coeur (jducoeur) wrote,
Justin du Coeur
jducoeur

Microsoft adding Code Contracts to C# / .NET

Fairly important news for anybody doing programming in the Windows world: Microsoft is continuing to steal all the best ideas from other languages, and in this case is adding Contracts to the .NET library.

Contracts have been around for a while now, but this is the highest-profile implementation to date. The high concept is that ordinary signatures aren't sufficient to completely describe the behaviour of a class: to really describe how the class *works*, with deep static checking, you need to be able to describe it in more detail. Classic examples of contracts include "values passed to this method must be non-zero", or "this method can never return null".

What makes Contracts interesting is that they allow much deeper static evaluation of the code, so that the compiler can ensure that the Contract is always true, providing warnings any time something happens that might violate it. They're kind of like assertions, but where assertions only work at runtime, many Contracts can be enforced at compile time. The implementation isn't quite perfect yet -- they've bolted Contracts into the library, not the language, so they're still a tad clunky yet -- but it already provides impressive power. (For instance, they are showing that the compiler implicitly tests for universal contracts such as potential divide-by-zero errors and null references.)

Along with Contract support, they are releasing a new tool called Pex, which "explores" the problem space and exercises the method in various ways, checking for assertion and Contract violations. Again, not a new concept, but this is going to be a much wider release than such tools have gotten before. As far as I can tell, Pex is intended to obviate much of the need for manually-written unit tests, by generating and exercising all the obvious tests automatically.

There is an interesting talk available online, which describes the new Contract system and Pex. Well worth watching for any serious programmer, since the implication is that Contracts are about to become mainstream -- whether or not you're programming in .NET, I expect that they'll become pretty commonplace over the next couple of years. And this is definitely for the best: if you're running a compiled language, Contracts are a good step towards reducing many kinds of common errors...
Tags: programming
Subscribe
  • Post a new comment

    Error

    Anonymous comments are disabled in this journal

    default userpic

    Your reply will be screened

    Your IP address will be recorded 

  • 3 comments