0

Possible Duplicate:
.net 4.0 Code Contracts. When to use? When are they a waste of time?

I started to read the full documentation of the .NET Code Contracts and I noticed that you can specify the compiler not to emit the code corresponding to your contracts. But I was wondering WHY someone would want to do that?! I mean, from the documentation, code contracts are about specifying pre / post / invariants about your code.

Looking at another question .net 4.0 Code Contracts. When to use? When are they a waste of time?, it seems that contracts should guard against invalid state of an object, but then again, why would I want to disable them! In doing so, wouldn't I open the door for a mountain of problems?

Should they be used as business validation, like making sure that a startDate <= endDate or should I use the good old if-then-throw for business? If I disable the code contracts my class could now be in an invalid state.

So my question remains, why would I want to disable code contracts?

Community
  • 1
  • 1
Francois Joly
  • 307
  • 2
  • 11

2 Answers2

1

One scenario I can think of, if you have conditions that are expensive to test for, you may want to disable then in release builds, for performance gains.

Ortiga
  • 8,455
  • 5
  • 42
  • 71
  • is there a trade-off to be made between quality / stability and performance here? Since if you don't include these conditions, your object becomes open for invalid data, the second part of my question talk about if I should use these conditions in business validation. – Francois Joly Nov 07 '12 at 19:57
  • 1
    You should not use Code Contracts for validation of user data. The exceptions thrown are not designed to be caught, as they are intended to indicate a serious defect in the code. – porges Nov 14 '12 at 20:28
0

For the same reason Debug.Assert() is not compiled into the Release build. Sometimes you can detect a non-fatal invalid condition, and for some applications continuing execution is the desired behavior. Keeping code contract in the Release build is like using Trace.Assert().

I personally always keep contracts, as I don't even try to plan my code to somehow survive being in an invalid state.

Allon Guralnek
  • 15,813
  • 6
  • 60
  • 93