Monday, July 25, 2005

Design By Contract

When I first heard about DBC 4 years back, little did I know how important a role it can play in software development. But my experience in the past few years have made me wiser. I have seen so much of cluttered code where inside each method call, the first thing that is seen is the checking of all the parameters. (This is sometimes also replicated on the client side). How many times I have seen a try/catch for a condition that will never occur if the method is called correctly.

The "Design By Contract" paradigm eliminates all this. It specifies that a method should have a pre-condition, a post-condition and an invariant. At first, I found the concept of invariant a bit foggy to understand.

Well, actually it is very simple. An invariant is something (in a class) which does not change. Classes should specify their invariants: what is true before and after executing any public method.

If U are planning to incorporate DBC in Ur code, then check out :
http://jcontractor.sourceforge.net/
http://c2.com/cgi/wiki?DesignByContract

I feel "Unit Tests" can also play the role of checking Contracts as it is used in Extreme Programming. But may be both can be used to complement each other.

UnitTests tests for things which should happen. DesignByContract watches for things which shouldn't. These two categories overlap somewhat, but both techniques are still useful.