Recently I was working with some of the developers in a different office, I don’t normally see their code, so it was interesting to see how they are meeting various problems. Generally speaking, they are doing some nice looking work. The architecture that they are moving towards looks like it’s going a long way to solving a lot of problems, all good stuff.

One bit of code that I kept seeing really bothered me. It was a guard class that I kept seeing. I think it was a clone of a class from the here. The reason it bothered me was simply that it didn’t read well, I kept thinking that it was guarding against an exception. In reality it was guarding against an error condition and would throw an exception if the condition happened. For example:

Guard.Against<InvalidOperationException>(string.IsNullOrEmpty(serverName), "Server name must be provided")

I would much rather something that reads like this:

Throw<InvalidOperationException>
    .WithMessage("Server name must be provided")
    .When(string.IsNullOrEmpty(serverName));

Here’s my implementation of the class, thoughts?

public static class Throw<T> where T : Exception
{
    public static Thrower WithMessage(string message)
    {
        return new Thrower(message);
    }

    public class Thrower
    {
        private readonly string message;
        public Thrower(string message)
        {
            this.message = message;
        }

        public void When(Func<bool> predicate)
        {
            if (predicate())
            {
                throw (T)Activator.CreateInstance(typeof(T), message);
            }
        }

        public void When(bool condition)
        {
            if (condition)
            {
                throw (T)Activator.CreateInstance(typeof(T), message);
            }
        }
    }
}
view raw Throw.cs This Gist brought to you by GitHub.