0

I have seen code which includes Contract.Assert like,

Contract.Assert(t != null);

Will using Contract.Assert have a negative impact on my production code?

forsvarir
  • 10,749
  • 6
  • 46
  • 77
Imran Qadir Baksh - Baloch
  • 32,612
  • 68
  • 179
  • 322
  • 1
    hmm it depends.. ofcource it will have an impact on performance, but I belive you can *turn off* the contracts - so that they will *not* be executed. this is handy for code that is ready for production :) – Jens Kloster Aug 21 '13 at 12:20
  • If by "impact on performance" you mean returning from the function immediately should the assert succeed. It's unlikely that takes longer than the actual logic of the function. And ideally you would only ship code to production that's actually correct, i.e. the asserts do not fail. – millimoose Aug 21 '13 at 12:32
  • i like asserts, even though they mess up the code a bit, they save lots of time writing already written Unit Tesing Code. – Tomer W Aug 21 '13 at 13:20

3 Answers3

4

According to the manual on page 11, they're only included in your assembly when the DEBUG symbol is defined (which, of course, includes Debug builds, but not Release builds (by default)).

fourpastmidnight
  • 4,032
  • 1
  • 35
  • 48
1

In addition to the runtime benefits of Contract.Assert, you can also consider the alternative of using Contract.Assume (Manual section 2.5 page 11) when making calls to legacy code which does not have contracts defined, and if you like having the static warning level cranked up on high (e.g. static checking level more warnings or all warnings - level 3+ - and Show Assumptions turned on).

Contract.Assume gives you the same run time benefits as Contract.Assert, but also suppresses static checks which can't be proven because of the legacy assembly.

e.g. in the below code, with static checking enabled and warnings set to level 3 gives the warning : CodeContracts: requires unproven: someString != null when checking the contracts of MethodDoesNotAllowNull

 var aString = Legacy.MethodWithNoContract();
 MethodDoesNotAllowNull(aString); 

  private void MethodDoesNotAllowNull(string someString)
  {
     Contract.Requires(someString != null);
  }

With Legacy Assembly code:

  public static string MethodWithNoContract()
  {
     return "I'm not really null :)";
  }

Assume suppresses the warning (but gives the run time Assert benefit in debug builds):

 var aString = LegacyAssembly.LegacyMethodWithNoContract();
 Contract.Assume(aString != null);
 MethodDoesNotAllowNull(aString);

This way, you still get the empirical runtime benefit of the Contract.Assert in debug builds.

StuartLC
  • 104,537
  • 17
  • 209
  • 285
-1

As for good practices it is better to have a set of good unit tests. Then code contracts are not that necessary. They may be helpful, but are less important.

BartoszKP
  • 34,786
  • 15
  • 102
  • 130