Write documentation comments on every method, every member. This is the sixth in a series of posts on Code Gardening - the practice of making small improvements as you see them while you are working.

Well written documentation comments make it easier to understand the intent of the code that you’ve written. This will assist any developer who comes along after you - which might just be you, in six months time.

Consider this fragment of code from an earlier post:

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

    return result;
}

This routine isn’t difficult to understand, but taking the time to do so would slow you down - and you only have that luxury if you’re reading the definition, not at the point of consumption.

Adding a good documentation comment to this method makes the method easier to understand:

/// <summary>
/// Find a course based on its unique identifying code
/// </summary>
/// <param name="code">
/// The (case insensitive) unique code to use for the search.
/// </param>
/// <param name="throwIfMissing">
/// True if an exception should be thrown if the course is not found.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown if no course code is supplied.
/// </exception>
/// <exception cref="InvalidOperationException">
/// Thrown if no course is found with that code and throwIfMissing is true.
/// </exception>
/// <returns>
/// The course that was found, if any; or null if not found and throwIfMissing false.
/// </returns>
public Course FindCourseByCode(string code, bool throwIfMissing)
{
    code.MustNotBeEmpty(nameof(code));
    var result = _courses.FirstOrDefault(c => c.HasCode(code));
    if (result == null && throwIfMissing)
    {
        throw new InvalidOperationException("Course not found");
    }

    return result;
}

With this comment in place, Visual Studio Intellisense lights up with useful information about the method as it is used:

You can see how intellisense is showing information that you normally would need to read the implementation to learn. It’s also including information that isn’t immediately discernable from the code, like the fact the search is case insensitive.

The usefulness of these comments isn’t limited to intellisense, however - documentation generators like docFx and SharpDox will include the documentation in the generated website.

Comments

blog comments powered by Disqus