5

I saw an awesome demo of C# Code Contracts and I want to start implementing them into may code. I wish I had them in my code already. Where does one start?

I failed to take away any printed materials from the demo. Any suggested reading?

Any suggestions for a beginner with Code Contracts?

Thanks in advance for your help.

user1270384
  • 711
  • 7
  • 24
  • 53
Rodney Hickman
  • 3,133
  • 11
  • 53
  • 83
  • 2
    http://devjourney.com/blog/code-contracts-part-1-introduction/ – albertjan Apr 18 '12 at 19:46
  • 2
    Beware that the Code Contracts annotations in the .NET Framework BCL are somewhat spotty. For example, many methods that always return a non-null object (unless it throws, of course) aren't marked as such. This forces you to litter your code with null checks or `Assume` calls in order to satisfy the static analyzer. – phoog Apr 18 '12 at 21:10
  • 2
    @phoog that is correct, but the Code Contracts team has been working to add contracts to more and more of the BCL, so this has been improving almost every release. – Andy Apr 19 '12 at 12:23
  • @Andy Thanks, that is very good to know. I must admit it's been a long time since I looked at Code Contracts, so I will have a look at the latest versions and I will certainly keep checking in the future. – phoog Apr 19 '12 at 14:28

2 Answers2

6

I'd start with this Wiki which describes Design by Contract. Then dive into the documentation on MS' implementation. To actually work it into your code, I suppose you could start almost anywhere, but maybe start with areas that are least likely to have an impact. So maybe add some Contract.Requires to ctor arguments, if appropriate. When you're more comfortable, you can add them to interfaces, but be aware this may blow things up... but in a good way. Errors or warnings mean you're violating DbC, and likely the Liskov Substitution Principle.

Andy
  • 8,432
  • 6
  • 38
  • 76
5

The user manual provided at the Code Contracts project page, gives a very good description of how to use and the possibilities of Code Contracts.

Xharze
  • 2,703
  • 2
  • 17
  • 30