views:

99

answers:

2

I recently saw this video http://channel9.msdn.com/pdc2008/TL51/ about the managed Contract tools library which certainly looks very interesting. Sadly it seems they won't include this into the language itself which would have been more elegant as in Spec#. It would be nice to have is as both options in C#4.0 in fact as the Contracts adds a lot of noise to the business code.

Have anybody here used it and have some real world feedback? Could you also add contracts to class Properties and even variables? Something like

decimal Percentage (min 0, max 1)
string NotNullString (not null, regex("??"))

would maybe been nice.

+2  A: 

I'm trying it, but I think that the library is too young to be used seriously on big projects, at least with the static checks enabled: compiling is very slow and the specific warning are not very clear to read.

Runtime checkings can be used without problems, because they seems to be implemented as Debug.Assert. At least you document methods.

In order to add contracts to properties i would add constraints to the set property, but in this specific case I think it would be better writing a class that could actually encapsulate the requirements, allowing the construction of good objects only. Anyway:

    private decimal _Percentage;
    decimal Percentage
    {
        get{ return _Percentage;}
        set
        {
            CodeContract.RequiresAlways(value <= 1);
            CodeContract.RequiresAlways(value >= 0);
            _Percentage = value;
        }
    }

p.s: It seems to me that the trend in C# goes in the dynamic typing direction, instead of going to the strict and strong typing coding methods. I think that DbC works better with strong typing, at least because it let you add more requirements to types and to functions.

Zen
+1, very interesting. I guess I will wait a bit before trying the libtrary myself. As long as the dynamic features are implemented well they have earned their place in c#, I could not imagine being without Linq anymore
TT
A: 

It seems the Contract Library could be a nice fit for Linq2Sql. Define fields and constraint in your sql database and contracts could be generated for you. This could be a nice introduction to Contracts.

TT