Names for method should say what they do, but not how they do it.

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

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;
}

Code that invokes this method might look like this:

var course = Find("COMP");

The name of this method is superficially good - but we can easily do better.

Unless this method gains context by living in a CourseRepository (or something similar), the name should indicate what’s being found - a Course.

Also, given that the names of the parameters are only visible in the implementation, and not at the call site, it would be useful to declare the kind of search. Note that we don’t want to constrain the implementation, so this should declare the behaviour of the search, not how it happens to be implemented.

Renaming the method to FindCourseByCode we get implementation :

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

    return result;
}

And now the code that invokes this method might look like this:

var course = FindCourseByCode("COMP");

Using a method name that is explict about the intention of the method makes it easier to read the calling code.

Prior post in this series:
Use Standard Library Features
Next post in this series:
Use Full Words, Not Contractions

Comments

blog comments powered by Disqus