We are building business application not API for others to use, in this case, I prefer to use our validation logic in the if/then/throw model. I was told, it is better to use Code Contracts. I do not see any benefits, is there any obvious benefits that I am not seeing? I see problem using code contracts since it is static method call and also there is some code injection happens after the compile phase. Thanks
1 Answers
There are two obvious benefits:
(1) The code is much easier to read.
Contract.Requires(someParam != null && someParam.SomeValue != 0);
versus
if (someParam != null && someParam.SomeValue != 0)
throw new ArgumentNullException("someParam", someParam, "someParam can't be null and someParam.SomeValue can't be zero.");
Also, with Code Contracts, the predicate code is automatically put into the failure message so you don't need to write an explicit message like you do with normal exceptions.
(2) You can run Code Contracts static analysis on the code and it can find errors for you.
There are some less obvious benefits:
(3) You can generate documentation for the code contracts in the XML doc files.
(4) You can use Contract.Ensures()
to express postconditional constraints. This allows you to avoid a lot of code like if (item.Property1 != null && item.Property1.Property2 != null) ...
because you will know that neither Property
or Property2
can be null.
(5) The code contracts form a block that is clearly separate from the rest of the code.

- 104,400
- 10
- 158
- 276
-
+1 Several benefits indeed, too bad the code rewriting has such a big impact on performance :( – vc 74 May 15 '13 at 08:43
-
@vc74 I've done some timings for preconditional checks, and it has very little impact on performance. Where are you seeing problems? Do you mean the effect it has on compilation times? – Matthew Watson May 15 '13 at 08:44
-
I've migrated my old style preconditions to code contracts for one of the applications I maintain, each project within the solution (~10) takes an additional 3s (!) to compile – vc 74 May 15 '13 at 08:47
-
1@vc74 Ok, so you're talking about the compilation time. It does add some overhead of course, but it's well worth it IMO. :) I'm guessing that it will be added to the compiler properly in a future version which will really help - not of use right now of course, but still. – Matthew Watson May 15 '13 at 08:53