문제

Could I start using CodeContracts instead of:

if (XXX == Y)
    throw new ArgumentException("bla bla");

How does it work if I develop a library and my library users do not use CodeContracts?

도움이 되었습니까?

해결책

Assuming that the code using code contracts is run through the binary rewriter, it will throw exceptions like code you posted. The re-writer goes through the code and replaces the contract code with argument checking etc. It's kinda like aspect oriented programming. It injects code to handle situations for you after you've compiled it.

If they don't use Code Contracts they will not get the benefit of having static analysis performed which is designed to look at the contract and warn them they might get an error based on the contract and their code.

Code Contracts

다른 팁

To the point: It's possible to write statements like this

Contract.Requires<ArgumentNullException>(argumentToCheck, "argumentToCheck");

If you enable the Runtime checker in your build configuration, the rewriter will rewrite preconditions like this to an ordinary ArgumentNullException.

Callers of your code will be shown an ArgumentNullException, or whatever exception you provide, regardless of whether or not they have Code Contracts installed.

I have been using code contracts and for casual use, they address 2 code problems for me that didn't have nice solutions earlier:

  • checking return values checking
  • invariants appear to be a poorly named combined parameter check/entry point and return value/exit point assertion.

I could declare a temp variable for the return value and assert some things before return it, but it's extra friction.

checking parameters already had a solution: throw ArgumentException.

Code contracts adds one tiny thing to ArgumentException-- it makes you check arguments very early, which in my opinion is a good thing.

There is much more going on with Code Contracts, but I've just dipped my toe into and I don't have the edition that does super-comprehensive static checks. I plan to work my way up to using Code Contracts more completely, and once I have done so-- it will be more elegant to check parameters using the same framework instead of switching back and forth between Code Contracts and if/then/throw ArgumentException

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top