Monday, November 15, 2010

CodeContracts - yum

I just spent the weekend converting a little in-home code over to using the new .Net4 code contracts. My opinion: FANTASTIC.

My initial goal for the weekend, was to create a simple demo, to see whether I'm in the
A) keep unit-tests for contracts. Or
B) don't unit test a contract.
Camp. Opinion on-the-net seams divided over this, so I wanted to make my own mind up by using CodeContracts in a non-trivial piece of software.

What I found: my code was full of potential bugs :( The starting code base wasn't my best work, but I did have a good set of unit tests for it. I was expecting the code-contracts to highlight some weekneses, but it ended up forcing me to think a lot more about the possible problems, so I spent my time fixing what looked like decent code.

To that end I now think
1. Writing verifiable code with CC is a must do.
1.1 it takes a lot more time (script kiddies will hate it), but better time now then bugs later.

2. The current lack of static-checking for Contract.ForAll and Contract.Exists is a problem.
3. Using Contract.Assume is a crappy, currently needed hack.

4. CC tutorials and examples need to focus on Contract.Ensure, not Contract.Requires. To my mind being able to express guarantees on what-my-code does is more important than expressing limits that clients need to obey.

5. Think of CC as like writing tests, docx, and defensive programming all rolled int a couple of code lines.

6. CC forces you to think far more critically. Sometimes, you won't believe it's warnings. Sometimes it'll be because the static checker isn't smart enough, but mostly it'll be the developer isn't looking close enough.

7. CC is NOT just for null checks, if you only Ensure not-null, your missing a lot of the power.

Requires that use more than the input params need to be simple for callers to check.

Sample contract on a duel-construct such as ui ctor + create.
Simple contract on disposable / disposed object.

A short list of C# coding issues.

Injecting services into entities It been bugging me for a while now that to use services in a entity can be a bit of pain. It usually starts...