DevLabs is an initiative from Microsoft to reach out broad developer audiences with prototypes of technology that will be incorporated into products later.This is a very good opportunity for developers to play around with upcoming product features and provide their feedback to Microsoft.Recently I came across the Design By Contract related libraries released at DevLabs.This is named as "Code Contracts" and this will be shipped as part of .NET Framework 4.0 which is currently in CTP stage.In this post I will be discussing about the Design By Contract in general rather than the features provided by this library.
So specification/contracts based on which two objects communicate with each other has three major components:
- Precondition - PreConditions are to be satisfied by the client by prior to invoking a routine(i.e. in simple terms we can think of providing proper input/parameter values).This can be viewed as an obligation for client and possible benefit of the supplier.
- Postcondition - Postconditions are to met by the supplier i.e. return value or supplied product should be as promised by the contract or specification.This is a responsibility of supplier and benefit to the client.
- Invariant - This is a bit different from the other two and is very specific to object oriented systems.This is a condition which must hold good for a class unlike the other two which are at method level. Consider the example of BankAccount class.It has a member balance and routine Withdraw as shown below:
public int id;
public double balance;
public void WithDraw(double amount)
balance -= amount;
Here an invariant will be BankAccount.balance>0 and precondition for method WithDraw can be amount>0.
Now you might be thinking that we can very easily implement this using additional if-else checks inside the method (for preconditions/invariant) and client code (for post conditions).But doing that for every class/method will result in an unnecessary cluttered code.So the languages like Eiffel, that is known to support Design By Contract actually provides special keywords using which these specifications can be expressed in a clean manner as shown below:
put (x: ELEMENT; key: STRING) is
-- Insert x so that it will be retrievable through key.
count <= capacity
... Some insertion algorithm ...
item (key) = x
count = old count + 1
With DevLabs Code Contract,the contract specification is not part of C#/VB.NET language but provides a declarative programming model to specify the contract using Attributes.If you are interested to take a look into this please go to
I will post my opinions as I start exploring this library.