DaedTech

Stories about Software

By

Poor Man’s Code Contracts

What’s Wrong with Code Contracts?!?

Let me start out by saying that I really see nothing wrong with code contracts, and what I’m offering is not intended as any kind of replacement for them in the slightest. Rather, I’m offering a solution for a situation where contracts are not available to you. This might occur for any number of reasons:

  1. You don’t know how to use them and don’t have time to learn.
  2. You’re working on a legacy code base and aren’t able to retrofit wholesale or gradually.
  3. You don’t have approval to use them in a project to which you’re contributing.

Let’s just assume that one of these, or some other consideration I hadn’t thought of is true.

The Problem

If you’re coding defensively and diligent about enforcing preconditions, you probably have a lot of code like this:

public void DoSomething(Foo foo, Bar, bar)
{
  if(foo == null)
  {
    throw new ArgumentNullException("foo");
  }
  if(bar == null)
  {
    throw new ArgumentException("bar");
  }

  //Finally, get down to business...
}

With code contracts, you can compact that guard code and make things more readable:

public void DoSomething(Foo foo, Bar, bar)
{
  Contract.Requires(foo != null);
  Contract.Requires(bar != null);

  //Finally, get down to business...
}

I won’t go into much more detail here — I’ve blogged about code contracts in the past.

But, if you don’t have access to code contracts, you can achieve the same thing, with even more concise syntax.

public void DoSomething(Foo foo, Bar, bar)
{
  _Validator.VerifyParamsNonNull(foo, bar);

  //Finally, get down to business...
}

The Mechanism

This is actually pretty simple in concept, but it’s something that I’ve found myself using routinely. Here is an example of what the “Validator” class looks like in one of my code bases:

    public class InvariantValidator : IInvariantValidator
    {
        /// <summary>Verify a (reference) method parameter as non-null</summary>
        /// <param name="argument">The parameter in question</param>
        /// <param name="message">Optional message to go along with the thrown exception</param>
        public virtual void VerifyNonNull<T>(T argument, string message = "Invalid Argument") where T : class
        {
            if (argument == null)
            {
                throw new ArgumentNullException("argument", message);
            }
        }

        /// <summary>Verify a parameters list of objects</summary>
        /// <param name="arguments"></param>
        public virtual void VerifyParamsNonNull(params object[] arguments)
        {
            VerifyNonNull(arguments);

            foreach (object myParameter in arguments)
            {
                VerifyNonNull(myParameter);
            }
        }

        /// <summary>Verify that a string is not null or empty</summary>
        /// <param name="target">String to check</param>
        /// <param name="message">Optional parameter for exception message</param>
        public virtual void VerifyNotNullOrEmpty(string target, string message = "String cannot be null or empty.")
        {
            if (string.IsNullOrEmpty(target))
            {
                throw new InvalidOperationException(message);
            }
        }
    }

Pretty simple, huh? So simple that you might consider not bothering, except…

Except that for me, personally, anything that saves lines of code, repeat typing, and cyclomatic complexity is good. I’m very meticulous about that. Think of every place in your code base that you have an if(foo == null) throw paradigm, and add one to a cyclomatic complexity calculator. This is order O(n) on the number of methods in your code base. Contrast that to 1 in this code base. Not O(1), but actually 1.

I also find that this makes my methods substantially more readable at a glance, partitioning the method effectively into guard code and what you actually want to do. The vast majority of the time, you don’t care about the guard code, and don’t really have to think about it in this case. It doesn’t occupy your thought briefly as you figure out where the actual guts of the method are. You’re used to seeing a precondition/invariant one-liner at the start of a method, and you immediately skip it unless it’s the source of your issue, in which case you inspect it.

I find that streamlined contexting to be valuable. There’s a clear place for the guard code and a clear place for the business logic, and I’m used to seeing them separated.

Cross-Cutting Concerns

Everything I said above is true of Code Contracts as well as my knock off. Some time back, I did some research on Code Contracts and during the course of that project, we devised a way to have Code Contracts behave differently in debug mode (throwing exceptions) than in release mode (supplying sensible defaults). This was part of an experimental effort to wrap simple C# classes and create versions that the “no throw guarantee”.

But, Code Contracts work with explicit static method calls. With this interface validator, I can use an IoC container define run-time configurable, cross cutting behavior on precondition/invariant violations. That creates a powerful paradigm where, in some cases, I can throw exceptions, in other cases, I can log and throw, or in still other cases, I can do something crazy like pop up message boxes. The particulars don’t matter so much as the ability to plug in a behavior at configuration time and have it cross-cut throughout the application. (Note, this is only possible if you make your Validator an injectable dependency).

Final Thoughts

So, I thought that was worth sharing. It’s simple — perhaps so simple as to be obvious — but I’ve gotten a lot of mileage out of it in scenarios where I couldn’t use contracts, and sometimes I find myself even preferring it. There’s no learning curve, so other people don’t look at it and say things like “where do I download Code Contracts” or “what does this attribute mean?” And, it’s easy to fully customize. Of course, this does nothing about enforcing instance level invariants, and to get the rich experience of code contracts, you’d at the very least need to define some kind of method that accepted a delegate type for evaluation, but this is, again, not intended to replace contracts.

Just another tool for your arsenal, if you want it.

By

Microsoft Code Contracts

I’m currently working on an ongoing side project, and we’re using Microsoft Code Contracts, so I thought that I would create a series of posts documenting my experience with this as a new and curious user. The basic idea of it is to standardize and formalize preconditions, post conditions, and invariants in your classes.

For instance, let’s say that you work on a C# project in which you can’t really trust your users or your dependencies not to do unpleasant things. You might create a class that looks like this:

public class CarService
{
    private ICarDao _carDao;

    public CarService(ICarDao dao)
    {
        if(dao == null) 
            throw new ArgumentNullException("dao");
        _dao = dao;
    }

    public void SaveCar(Car car)
    {
        if(car == null) 
            throw new ArgumentNullException("car");
        else if(car.Engine == null) 
            throw new InvalidOperationException();
        //etc
        _carDao.Save(car);
    }
...
}

This is the epitome of defensive code, and it’s a smart thing to do in the context that I mentioned. At the beginning of each method, you ferret out the things that will create problems for operations (precondition violations) and throw if they aren’t satisfied. In the constructor, you, perhaps, enforce some class invariants (i.e. our service class basically can’t do anything if its data access reference is null).

That’s fine, but it creates a certain amount of boilerplate overhead, and it’s somewhat ad-hoc. Code Contracts standardizes it:

public class CarService
{
    private ICarDao _carDao;

    public CarService(ICarDao dao)
    {
        Contract.Requires(dao != null);
        _dao = dao;
    }

    public SaveCar(Car car)
    {
        Contract.Requires(car != null);
        Contract.Requires(car.Engine != null);
        //etc
        _carDao.Save(car);
    }
...
}

As you can see, the defensive coding boilerplate becomes a little less verbose. But what’s more is that Code Contracts will also generate compiler warnings when client code does not or may not satisfy the preconditions. So, if I had the code below in another class, I would be shown a compiler warning that the precondition was not satisfied.

public void DoSomething()
{
    CarService myService = new CarService(new CarDao());
    myService.SaveCar(null);
}

Another cool facet of this is that you can express post conditions in a way that you really can’t with the guard/throw paradigm. For instance:

public class Foo
{
    private int _counter;

    public void Increment()
    {
        Contract.Ensures(Contract.OldValue(_counter) + 1 == _counter);
        _counter++;
    }    
}

As you can see, we’re sticking a post condition in here that advertises what the method will guarantee when it is finished. In this fashion, client code that may specify its own pre-/post-conditions and invariants has more to work with in terms of proving its own conditions. Also, anyone reading the code can tell what the author intended the method to do (and what side-effects, if any, it might have). This is where your contract doubles as correctness enforcement and documentation. Comments may lie after enough time and changes, but the contracts won’t–you’ll get warnings or runtime errors if that documentation goes out of date.

The final thing that I’ll show in this introductory post is the notion of a class invariant. Let’s take a look at our previous car example, but dressed up a little.

public class CarService
{
    private ICarDao _carDao;

    [ContractInvariantMethod]
    private void ObjectInvariant()
    {
        Contract.Invariant(_carDao != null);
    }

    public CarService(ICarDao dao)
    {
        Contract.Requires(dao != null);
        Contract.Ensures(_dao != null);
        _dao = dao;
    }

    public SaveCar(Car car)
    {
        Contract.Requires(car != null);
        Contract.Requires(car.Engine != null);
        //etc
        _carDao.Save(car);
    }
...
}

Here, I’ve added a method decorated with a Code Contracts attribute. The end effect of this is to create an object invariant – essentially, an implied pre- and post-condition for every method in my class. Now, the code is future-proof. If anyone adds methods to this and tries to set _carDao to null, they will get warnings/errors, depending on the mode of Code Contracts. (I’ll go into this in a future post.) If someone derives from this class and tries the same thing, the same result will occur. We’ve locked up an invariant as bulletproof. The other nice thing is that if you move this logic into an invariant method, you don’t have to check the _carDao for null in all of your methods, cluttering them with useless checks.

In future posts, I intend to cover the different modes of Code Contracts, some more advanced features, some more depth information, its interaction with the Pex utility, and a utility that I’m working on which provides wrappers for C# library classes that enforce the No-Throw guarantee.

Acknowledgements | Contact | About | Social Media