Tuesday, January 18, 2011

Code Contracts - a simple idiom

I've been experimenting with .NET 4 Code Contracts for a couple of months.
Contracts themselves are simple enough to understand. The potential to produce stabler code, improve readability, and some help with the pesky 'object null' problem makes them very attractive.
A few blog posts, such as Billy McCafferty, and a series from Derik Whittaker help get up to speed.

My initial work with Contracts started with simple require not null type contracts, and soon escalated to more useful contracts such as 'no nulls in a list', FileInfo.Exists == true. What I found was a simple rule helped to limit what to declare for a contract:

Don't Require more than what a caller can simply (one-line) Ensure.

It is easy for a caller to check an object is not-null before calling a library... but out-of-the-box checking for more complex constraints, such as list contains no-nulls made the code less readable. The idiom above doesn't stop me from using more complex constraints, but it does ensure I provide a simple (one line) way for callers to ensure the constraint.

Tuesday, January 11, 2011

spring.net multiple validators with one action.

I had an interesting problem at work the other day.
I needed to perform a number of validations against an object, and report a single error message.
In this project we're using Spring.net's validation framework.

Out of the box, spring.net validation doesn't provide any easy way to report a single error for multiple validations. But here's a simple trick to work around this:
1. Use a validation group to group all the validations.
2. Don't include an action (message) on the included validations.
3. Set the group's 'Actions' property to a new list of Spring.Validation.Actions.ErrorMessageAction items.

<v:group>
  <v:property name="Actions">
    <list>
      <object type="Spring.Validation.Actions.ErrorMessageAction">
        <constructor-arg index="0" value="error.MyError" />
        <constructor-arg index="1" value="MyErrorParam" />
      </object>
    </list>
  </v:property>

  <v:validator test="Prop1" />
  <v:validator test="Prop2" />
  <v:validator test="Prop3" />
</v:group>

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...