Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 989
punkouter Avatar asked Jun 24 '10 15:06

punkouter


2 Answers

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.

like image 23
Andrey Avatar answered Oct 05 '22 10:10

Andrey


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.

like image 56
kemiller2002 Avatar answered Oct 05 '22 11:10

kemiller2002