We at d-fens use Microsoft Code Contracts every day. And certainly with every great tool there are some things that might benefit from some improvement – and code contracts are no exception. There is one particular annoying thing in that the error message for Contract.Result exceptions strips the generic parameters from it. This in essence means, that every time we get a post condition failure from a null check like Contract.Ensures(null != Contract.Result()) we end up with an error message like this:

Postcondition failed: null != Contract.Result()

As the type Permission is left out, we cannot really tell by the message what actually has been null. Luckily, there is an easy workaround for this: by defining a constant default(Permission) variable we can use this for our null check:

private const Permission UNKNOWN_PERMISSION_NAME = default(Permission);

public Permission GetPermission(string name)
{
    Contract.Ensures(UNKNOWN_PERMISSION_NAME != Contract.Result<Permission>());

    // ...
}

Now we will get a much more user-friendly message like this:

Postcondition failed: UNKNOWN_PERMISSION_NAME != Contract.Result()

As we are using contract messages as error messages in our API code, we now can easily create more meaningful error messages without resorting to custom messages:

CodeContract error message
CodeContract error message

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.