问题
I have been studying .NET 4.0 Code Contracts and looking on stackoverflow as well at question regarding this.
I still have never come across any sample code that uses code contracts so that gets me wondering.. is this really useful ? Or maybe its only useful one your code reaches a certain complexity? Anyone out there using Code Contracts and really glad they did?
Seems to me that all Code Contracts are is a Assertion on what goes in and what goes out of a method with the addition of being able to try to figure out the values going in and out at compile time... But then this is going to require more code on all your methods.. is it worth it ?
A benefit I noticed is it seems to me you can use code contracts kind of as a first line of unit testing... then when you write unit test to can avoid writing some of the more basic tests because the Code Contracts cover it already.. is that true ?
Will contracts work with WCF calls? I am guessing not since a proxy is created with you automatically that you cant change.
回答1:
I use them anytime i need to validate that an input parameter needs to have a specific value (number is positive, object is not null).
For outputs, I use them anytime I am certain that a return value should be in a certain state (not null for example).
Having contracts in the code ensures that an exception will be thrown the moment that an unexpected value crops up, and not further down in the code where objects may accidentally be left in a corrupted state because of an accidental assumption.
Personally, I think it makes the code a lot cleaner. The notation makes it a lot less to write (instead of using if(....== null)....). This way too Contract.Requires
is very up front in what it is trying to accomplish. When I see that I know that the code is evaluating that a parameter is in a certain state.
回答2:
there is field of study on contracts: http://en.wikipedia.org/wiki/Design_by_contract it was long before they were introduced in .net.
Code contracts are useful to give answers to following questions:
- What does method expect?
- What does method guarantee?
- What does method maintain?
If you can write small and readable contract for those questions then use it.
回答3:
One of the primary reasons to use CodeContracts is to enable Static Analysis to detect violations of the CodeContracts so they're caught early rather than resulting in bugs or unknown behavior at runtime.
You can disable runtime enforcement of CodeContracts if you want to.
Another good reason to use them is to add Contract definitions to XML Code Comments to enhance API documentation. This also works with Sandcastle though there are some tweaks necessary to integrate them fully. Refer to section 8.3 in the Code Contracts User Manual dated 2/4/2011 (or later) available at http://research.microsoft.com/en-us/projects/contracts/userdoc.pdf
来源:https://stackoverflow.com/questions/3111332/net-4-0-code-contracts-when-to-use-when-are-they-a-waste-of-time