Code Contracts for
Code Contracts includes a static checker program for verifying both explicit and implicit (null references, array bounds, etc.) code contracts. Runtime (dynamic) contract checking can use marked series of If-Then-Throw guard clauses as in:
if ( x == null )
throw new ArgumentNullException("x");
if ( y < 0 )
throw new ArgumentOutOfRangeException(...);
Contract.EndContractBlock();
(so you don't waste perfectly good guard clauses) as well as the standard, explicit code contracts like:
Contract.Invariant(this
.y >= 0);
Contract.Assert(this.x == 3,
"Why isn't the value of x 3?");
Contract.Requires(x ! = null,
"DANGER -- missles fired!");
Code Contracts defaults at runtime to throwing an exception (System.Diagnostics.Contracts.ContractException) when a contract is violated (this behavior is configurable).
I have not tried Code Contracts (or any code contract mechanism) yet, but the idea is intriguing because it lets the computer do something it does well (exhaustive examination of your code in tedious detail) thereby freeing you to work on the higher-level aspects of your program, just as C freed us from assembly language bookkeeping and Perl/Java/VB.NET etc. free us from C language bookkeeping.
If anyone has experience with code contracts for any language (positive or negative), please comment.
(Ob. Perl ref. -- see Moose and Class::Contract among others...
But what's the overhead? (Score:1)
Hi Mark
I can understand the theoretical arguments for all these asserts, but I can't actually envision writing such code in the real world.
And I don't think it's good enough to say people ought to - the simple fact is that, in general, they won't.
So, what are your thought on this :-)?
Re: (Score:1)