Objects and methods in the standard libraries doesn’t need to be written nor debugged.

Consider this fragment of code - this is where we ended up after the last post.

public Course Find(string cde, bool throwIfMissing)
{
    foreach(var c in _courses)
    {
        if (c.HasCode(cde))
        {
            return c;
        }
    }

    if (throwIfMissing)
    {
        throw new InvalidOperationException("Course not found");
    }
    return null;
}

The loop in this routine is well written, and obviously correct - but this is mostly because the test is a simple one. It’s easy to see how this might go wrong if the test were more complex.

In 2007 we had the release of C# 3.0 with the included LINQ query language, along with the support in .NET 3.5 for working effectively with sequences of values.

These routines are well designed and robustly implemented - so lets use them to simplify this method.

The FirstOrDefault() extension method will return the first item in a sequence that satisfies the a given predicate. If no match is found, it will return the default value for the result type, usually a null. (Other related methods to research include First(), Single() and SingleOrDefault()).

Replacing the loop with the extension method, we get this:

public Course Find(string cde, bool throwIfMissing)
{
    var result = _courses.FirstOrDefault(c => c.HasCode(cde));
    if (result == null && throwIfMissing)
    {
        throw new InvalidOperationException("Course not found");
    }

    return result;
}

We’ve taken another step forward towards our goal of intention revealing code. There’s no way we can screw up writing a loop if we don’t have to write it ourselves. Better yet, this code is both shorter and easier to read.

Prior post in this series:
Helper Methods
Next post in this series:
Intention Revealing Method Names

Comments

blog comments powered by Disqus