When you have any non-trivial condition - whether in an if, while or until statement - move the condition into a well named local bool variable to aid in readability. This is another in my series of posts on Code Gardening - the practice of making small improvements as you see them while you are working.

Consider this simple method that attempts to enroll a student in a particular class for study:

public bool TryEnrol(Student student, DateTimeOffset systemDate)
{
    if (EnrolmentOpens <= systemDate
        && systemDate <= EnrolmentCutoff
        && CurrentStudentCount < MaximumStudentCount
        && !Students.Contains(student))
    {
        Students.Add(student);
        return true;
    }

    return false;
}

Understanding the boolean condition isn’t overly difficult - at least the code has been well formatted to facilitate reading.

However, any developer reading the method has to take the time to parse out what each part of the expression means, and therefore what the expression as a whole is actually testing.

We can give each clause a descriptive name and make the condition trivially easy to understand:

public bool TryEnrol(Student student, DateTimeOffset systemDate)
{
    var enrolmentHasOpened = EnrolmentOpens <= systemDate;
    var enrolmentHasNotClosed = systemDate <= EnrolmentCutoff;
    var courseIsNotFull = CurrentStudentCount < MaximumStudentCount;
    var studentHasNotAlreadyEnrolled = !Students.Contains(student);

    if (enrolmentHasOpened
        && enrolmentHasNotClosed
        && courseIsNotFull
        && studentHasNotAlreadyEnrolled)
    {
        Students.Add(student);
        return true;
    }

    return false;
}

With this code, the conditions required for enrollment to succeed are very easy to see - they might even be clear enough that we could read the code to our end users to test if the logic was correct.

An additional benefit of this approach is that the variable name describes the intention of the condition, making it easier for errors to be identified during code review or debugging.

Prior post in this series:
Why Code Garden?
Next post in this series:
Don't work too hard

Comments

blog comments powered by Disqus