Guarding Against Multiple Empty Strings

Many of my C# methods include what is referred to as a guard clause.  It isn’t a complicated concept.  Simply the first few statements of a routine validates passed-in parameters and/or state of the object and immediately returns an error or gracefully exits to the function is constraints aren’t met.  If I’m not mistaken, this plays nicely with the Design by Contract approach to software design, but I no expect on the subject.  The bottom line is, a guard clause can really tighten and clean up your code because it will undoubtedly eliminate any number of nested conditional statements.

Consider the following sample taken directly from c2.com:

public Foo merge(Foo a, Foo b)
{
    Foo result;
    if (a != null)
    {
        if (b != null)
        {
            // complicated merge code goes here.
        }
        else
        {
            result = a;
        }
    }
    else
    {
        result = b;
    }
    return result;
}

Now with the guard clause…

public Foo merge(Foo a, Foo b)
{
    if (a == null) return b;
    if (b == null) return a;
    // complicated merge code goes here.
}

Much cleaner, eh? And that’s only two conditionals! Back to my point.  Many of my method include guard clauses.  Today I needed to validate that all three string parameters had a value.  In other words, each string’s length was greater than 0.

I started with my faithful Is-Not-Null-Or-Empty check:

string a = "a";
string b = "b";
string c = "";

if (string.IsNullOrEmpty(a) ||
    string.IsNullOrEmpty(b) ||
    string.IsNullOrEmpty(c))
    return;

But then I settled on this:

string a = "a";
string b = "b";
string c = "";

if (a.Length * b.Length * c.Length == 0) return;

What do you think?  Pretty hokey, right?

 

Comments

  1. In the latter example, it seems worth noting that the “settled on” approach will throw a NullReferenceException if any of the variables being checked are set to NULL, instead of “” (or empty string). For this reason alone the first, more verbose, approach should ultimately be utilized.

  2. @discordinoffice – Hey, you’re right. Assuming that null values were possible, the latter approach would bomb. Probably not the best approach after all. Thanks.

  3. @discordinoffice – You’re right…. and let’s say you have string A containing 1 000 000 characters, string B 1 000 000 more and string c is empty (not null). Then you have a mutiplication of 1 000 000 by a 1 00 000 then by 0. I don’t know if .net does “looks” at all params befrore doing the actual operation, but if not, you have a lack of performance, especially if you’re running that block into a loop. I, as a best pratice, would always consider usign String.IsNullOrEmpty and avoid using Length if not absolutly necessary. What do you think ?

closed