AJ's blog

August 1, 2009

Posting Guards: Guard Classes explained

Filed under: .NET, .NET Framework, C#, Software Developers, Software Development — ajdotnet @ 11:53 am

A colleague writing an article about code contracts recently asked me about some useful links about Guard classes, something I have been advertising for some time. ‘Sure’, I thought — and was taught otherwise.

There are certainly references to Guard classes. For example this one hinting at an implementation from MS Patterns&Practices, although an outdated one and no online documentation available. And this one talking about using Guard classes in combination with LINQ.

Still, nothing explaining the concept, nothing on Wikipedia, nothing anywhere. Can it be that Guard classes are far too simple to be worth mentioning? I don’t think so, because while the implementation certainly is simple, I wouldn’t have had to explain the concept that often if that where the reason.

So, what are Guard classes?

First of all, let’s make sure we’re taking about the same thing. Judging from the name, Guard classes are about guarding against something, but this can mean just about anything. Actually I found two incarnations: One, guarding against concurrent access, i.e. some kind of locks. And two, guarding against the passing of invalid parameters into a method – which is what this post is about. (You may have come across Guard classes by the name of ArgChecker, ArgumentHelper, or something similar, or as single helper methods appearing where they don’t belong.)

Straight to the matter: Have a look at the following example:

IEnumerable<Employee> FindCustomers1(Guid companyID, EmployeeFilter filter)
{
    IEnumerable<Employee> result= null;
    if (companyID!=Guid.Empty) // only hit DB if we have to
    {
        using (DatabaseDataContext context = new DatabaseDataContext())
        {
            result = from e in context.Employees
                         where e.FirstName == filter.FirstName && e.LastName == filter.LastName
                         select e;
        }
    }
    return result;
}

While probably doing its job properly, this method isn’t exactly defensive. The issue should be apparent: What happens if the caller passed null for the filter? Not that he is expected to, quite the opposite, but anyway?

You could try to handle that in code and it would probably lead to some ugly code, as Abby rightly complained about. And to be blunt, that approach is wrong right from the start. If caller is not supposed to pass null values into our method, why should we clutter our code with conditions that aren’t supposed to happen anyway.

The better solution is getting rid of unwanted null values by making them illegal. And not only by politely asking in the documentation (and please RTFM); rather make it unmistakably apparent, punish any violation, make it impossible to bypass. In other words, check the parameter and throw an ArgumentException.

On second thought, the same reasoning applies also to the properties of our filter object, so we may end up writing the following code, prone to becomes ugly itself:

if (filter == null)
    throw new ArgumentNullException(„filter“);
if (filter.FirstName == null)
    throw new ArgumentNullException(„filter.FirstName“);
if (filter.LastName == null)
    throw new ArgumentNullException(„filter.LastName“);

And we actually did expect some content, so why not go ahead and do some other vanity checks:

if (filter.FirstName == „“)
    throw new ArgumentNullException(„filter.FirstName“);
if (filter.LastName == „“)
    throw new ArgumentNullException(„filter.LastName“);

But wait. An empty string is certainly not null. Unfortunately there is no StringEmptyArgumentException. Should we use an ArgumentOutOfRangeException? Or an InvalidOperationException, not an ArgumentException at all? Derive a new one? ArgumentOutOfRangeException may look nicely to me, but my team mate just settled with ArgumentNullException, which is at the least an inconsistency… .

And what the heck, this is way too much code for nothing anyway. And so we end up not checking our parameters and hoping for the best…?

Now consider this code:

IEnumerable<Employee> FindCustomers2(Guid companyID, EmployeeFilter filter)
{
    Guard.AssertNotNull(filter, „filter“);
    Guard.AssertNotEmpty(filter.FirstName, „filter.FirstName“);
    Guard.AssertNotEmpty(filter.LastName, „filter.LastName“);
    
    IEnumerable<Employee> result = null;
    if (companyID != Guid.Empty) // only hit DB if we have to
    {
        using (DatabaseDataContext context = new DatabaseDataContext())
        {
            result = from e in context.Employees
                         where e.FirstName == filter.FirstName && e.LastName == filter.LastName
                         select e;
        }
    }
    return result;
}

We just replaced 5 ugly conditions (10 LOC) with 3 calls. Let me rephrase that: We replaced a bunch of code detailing some implementation with 3 lines revealing the intention – way more readable. Wow! By centralizing the checks, we were able to provide more convenience (putting the null and string empty check in one method), we ensured consistent behavior, we improved the calling code considerably. And finally, we even added some more information to the exception, as you will see in the implementation:

[DebuggerStepThrough]
static public void AssertNotEmpty(string arg, string paramName)
{
    if (arg == null)
        throw new ArgumentNullException(paramName,
            „Argument ‚“ + (paramName ?? „<missing>“) + „‘ should not be NULL!“);

    if (arg.Length == 0)
        throw new ArgumentOutOfRangeException(paramName, arg,
            „Argument ‚“ + (paramName ?? „<missing>“) + „‘ should not be empty!“);
}

You don’t want to put that code in every method. But you do want to call the Guard method, don’t you?

Now that we have established what Guard classes are, let’s look at …

What are Guard classes about?

So far I introduced Guard classes form the coding level, merely as convenient helper classes. But there’s some broader meaning to them, namely in the following areas:

  • Contracting
  • Self preservation
  • Robustness

Contracting.

Contracting as a means has gained attention as important aspect of SOA service design, and also as development approach, namely design by contract. Contracting may be a major undertaking if it comes to SOA services, yet it can also be employed on a much lower level, designing the public interface of a class.

A little simplified, a contract of a class or service consists of

  • Functional contract: Specifies the operations, the semantics, required call sequences, runtime behavior, error conditions and behavior. Some of this may be expressed using code, some may not.
  • Data contract: Details parameters and return values, in other words the data that is exchanged during the operations. It defines the legal shape and values of the data, restricting it first by data types, secondly by additional demands, such as stating which parameter is mandatory, which content is required, and which values it is limited to beyond what the data type mandates. Also interdependencies between fields, and so on.
  • Some other aspects, but that’s not relevant right now.

As you see, the data contract goes beyond what the type system is capable to enforce. And Guard classes may serve as a means to express some of those aspects in code. Thus, Guard classes serve to enforce the contract of a class. And since these calls are that obvious, the code is self-documenting its preconditions quite nicely.

Note 1: Of course this makes only sense with regard to the technical contract that has to be met by the calling code, i.e. the developer, not a business contact that has to be met by the user. See my post on error handling and responsibilities for more on that topic.

Note 2: In terms of design by contract, Guard classes express the preconditions of an operation, something that has been baked into other programming languages right from the start.

Self preservation.

If you are working in a team, you inadvertedly have to work with other team members. Good ones, bad ones. And you may want to protect yourself against the later… .

Face it: If a NullReferenceException arises, the developer who wrote that particular code fragment – mayhap you – is held responsible (shot on first sight, so to speak). Even if it turned out later that the calling code passed some illegal null value… . Well, problem solved, but the stigma sticks, and anyone will only remember that the exception was thrown in your code.

How do you protect yourself against that? Guard classes. If the calling code just passed some crap data – despite you having told that guy what to pass a hundred times – just throw it right back into his face. That’s what ArgumentExceptions are for: complaining loud and clear about someone unduly misusing your code. Be the accusator, not the accused!

BTW: If you’re on the callers side and the method you just called returned a value, you may achieve something similar with Debug.Assert.

For example if you had written that code above, and I knew you to be a sloppy developer, I would certainly check the return value. And if I were as mean as you are sloppy, I would deliberately call it passing Guid.Empty as companyID. And if you dared to hand back that pesky null instead of an empty enumeration I would … .

Well, never mind. You‘re not sloppy, I‘m not mean, and I only put that bug in to stress the fact that Guard classes only work up the call chain, not down. (And yes, it’s a bug to return null in the above case. Methods supposed to be used in a LINQ context have to comply with LINQ demands, which are based on functional programming, which boils down to „no nulls please!“)

Robustness (or: making errors apparent).

Someone passed null or some other unwanted value to a method. There are actually two bad things that might happen:

  1. The application may crash further down.
  2. The wrong value may affect some data, but the application continues to work.

Number one may be bad, but at least the application crashes (which is a good thing!). Still, in this case Guard classes will help you identify the error far earlier, possibly avoiding a situation where you’ll have to hunt for the root cause of a problem. This should at least help diagnosing the problem.

Number two is far worse. It’s actually the very situation that you would want to avoid at any cost: A bug that stays unnoticed. A bug that occasionally produces wrong data, and that lingers around long enough to seriously affect data consistency to a degree that renders all data useless, because you have no way of knowing which data was affected and which not. Technically just a tiny slip, but in the long run these bugs are the most harmful.

To guard against these bugs Guard classes put up another safety net. Make sure the data coming in matches the specification.

Essentially both issues neatly demonstrate what „fail early, fails fast“ is about. Making errors apparent, prevent them from being obscured and from causing damage further down the line.

And that’s it…

Quite some task for a tiny little helper – but really worth the effort. Should you need some kick-start to employ this concept yourself, I posted the code for a Guard class here. Use it, enhance it, employ it to make you life easier.

HIH!

That’s all for now folks,
AJ.NET

kick it on DotNetKicks.com

13 Comments »

  1. Your Guard Classes are also known as ArgumentValidation in the Microsoft Enterprise Library.

    Enterprise Library documentation
    http://entlibcontrib.codeplex.com/Wiki/View.aspx?title=VAB%20Contributions&ANCHOR

    Some blogs althoug wrote something about it.
    Sample: http://odetocode.com/Blogs/scott/archive/2005/02/05/999.aspx

    But i like your article. Simple code, but never really documented. Thank’s a lot.

    Comment by michl86 — August 5, 2009 @ 8:44 pm

  2. […] my colleague AJ posted a really nice article about guard classes. He’s the first one who explained the topic as a […]

    Pingback by Code Contracts #7: Relation to Guard classes | .NET ... out of the dark — August 12, 2009 @ 1:18 pm

  3. You should take a look at CuttingEdge.Conditions ( http://conditions.codeplex.com ). I think you like what you’ll see there.

    Comment by Steven — September 10, 2009 @ 4:06 pm

  4. […] with some problems it will solve. For a great introduction into guard classes also have a look at Posting Guards: Guard Classes explained (AJ’s blog) I’ll integrate the complete source code with 100% covering unit tests and a little sample method […]

    Pingback by A Flexible Guard Class « Sven's Blog — September 8, 2010 @ 9:47 pm

  5. Excellent post. Explains the concept and implementations very well.

    Comment by santoshbenjamin — October 2, 2010 @ 8:54 pm

  6. […] Some days ago I’ve had an interesting technical discussion with a colleague of mine regarding the possibility of implementing Guard classes with Expressions in C#. Such a class enables easy argument checking in form of (technical) preconditions on method entry. Thereby the checking logic is encapsulated in the Guard class. […]

    Pingback by C#: Efficient retrieval of Expression values | Mind-driven development — October 11, 2010 @ 9:42 am

  7. Guy .. Excellent .. Wonderful .. I’ll bookmark your website and take the feeds additionallyI am happy to find a lot of helpful info right here in the put up, we need develop more strategies in this regard, thanks for sharing. . . . . .

    Comment by ZoryCihooro — September 21, 2011 @ 12:31 pm

  8. […] are called Guards or Validators. It’s their duty to keep your business logic safe. Invalid input values are […]

    Pingback by The Invisible Guard « Outlawtrail – .NET Development — October 4, 2012 @ 11:17 am

  9. I got this web page from my friend who informed me concerning this web site and now this time I am visiting this
    site and reading very informative posts at this place.

    Comment by Sofia — November 2, 2012 @ 3:42 am

  10. […] Posting Guards: Guard Classes explained « AJ’s blog. […]

    Pingback by .NET/C#: Some links on validation/guarding/checking « The Wiert Corner – irregular stream of stuff — December 5, 2013 @ 7:01 am

  11. […] at it: Don’t throw NullReferenceExceptions when validating the parameters of a method. Use Guard classes that throw ArgumentNullExceptions or Code Contracts that throw their own special type of exception. […]

    Pingback by Please not another NullReference | Outlawtrail - .NET Development — March 25, 2014 @ 7:24 am

  12. […] Posting Guards: Guard Classes Explained […]

    Pingback by try-catch – c# ¿Cuándo validar o cuándo lanzar una excepción? | Code2Read por Luis Aldazabal Gil — April 24, 2015 @ 4:03 am

  13. […] I recently wrote a post about guard classes (having not found any information either): https://ajdotnet.wordpress.com/2009/08/01/posting-guards-guard-classes-explained/ […]

    Pingback by .NET Guard Class Library? - Programming Questions And Solutions Blog — March 1, 2023 @ 12:04 pm


RSS feed for comments on this post. TrackBack URI

Leave a comment

Create a free website or blog at WordPress.com.