Should CodeContracts replace the regular ArgumentExceptions?

北慕城南 提交于 2019-12-12 14:44:24

问题


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?


回答1:


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




回答2:


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.




回答3:


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



来源:https://stackoverflow.com/questions/4490857/should-codecontracts-replace-the-regular-argumentexceptions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!