Thursday, April 13, 2006

How to write contract

The program languages which implement "Design by Contract (DbC)" are Eiffel, Digital Mars C++ Compiler and D programming language. All of these languages are never popular now. But, you can understand how to write the contract by reading the source code of DbC in these languages.

Sample code in the D's official site is the following:

long square_root(long x)
in
{
assert(x >= 0);
}
out (result)
{
assert((result * result) == x);
}
body
{
return
math.sqrt(x);
}


The in is contract pre-conditions. The out is contract post-conditions and able to get the variable result which is return value of the function.

D's assert is more useful than C's assert because it throws an AssertException. It can be caught and handled with catch{}.

No comments: