Code commenting

When I was a high school student learning programming, my programming teacher had an interesting code commenting requirement. He demanded at least one comment per page. He did not care what the comment was, just that there was at least one. He was more concerned with the quantity then quality. Every developer has his own opinion about comments. Some believe that comments are unnecessary and contribute to code bloat. On the other extreme, there are developers who are strong believers in commenting like my former programming teacher. I personally fall somewhere in between these two groups.
In my opinion, the code should be easy to read and maintain overtime. Comments should support the code by making it more understandable. I follow few guidelines in order to satisfy those objectives.

Comments should not dominate the code. Too many comments are distracting and make the code less readable. Whenever I find myself writing too many comments, I know it is a sign of a complex code or lack of understanding of the problem trying to solve. It is a signal for code refactoring. For instance, the following code has a redundant comment and does not provide any useful information:

// Multiply side A by side B
product = sideA * sideB;

The code should be self-documenting. We can refactor the code by eliminating the comment and renaming the “product” variable giving it a more descriptive name, “area”:

// Multiple side A by side B
area = sideA * sideB;

Now the intention of the developer is clear to anyone reading it. It is suppose to calculate the area.

Comments should describe code in more abstract terms. In the previous example, the comment was repeating the code and did not provide any additional beneficial information. It actually introduced a maintenance overhead. If the variable “sideA” were to be renamed to some other name (i.e. “shorterSideā€¯), the comment would also need to be modified to reflect the variable name change. A more abstract comment would eliminate the maintenance overhead and provide helpful information. We could modify the code by describing the intention instead of describing what the code does:

// Calculate the are of a rectangle
area = sideA * sideB;

Pseudo code makes good comments. When writing a new method, I write the pseudo code implementation first. It outlines major method functionality in abstract terms.

public string GetBillPayAccount(int customerNumber)
{
   // Verify arguments
   // Retrieve cutomer accounts
   // Generate bill pay account filter
   // Apply filter to the retrieved accounts
   // Return bill pay account
   return string.Empty;
}

Pseudo code method implementation allows me to analyze the solution and get a high-level view of the method. Once the pseudo code is finished, I proceed with writing the actual implementation. I do not throw the pseudo code away. On the contrary, I write the low-level implementation of the pseudo code using a programming language. I keep the pseudo code as a comment to the actual code. The product is abstract comments and concrete code.

public string GetBillPayAccount(int customerNumber)
{
   // Verify arguments
   if (0 > customerNumber)
   {
      throw new ArgumentException("Invalid customer number", "customerNumber");
   }
   // Retrieve cutomer accounts
   List<string> accounts = GetCustomerAccounts(customerNumber);
   // Generate bill pay account filter
   List<string, string> billPayFilter = CreateFilter(AccountStatus.Open,
                                                     AccountType.Checking);
   // Apply filter to the retrieved accounts
   string billPayAccount = FilterAccounts(accounts, billPayFilter);
   // Return bill pay account
   return billPayAccount;
}

Endline comments hamper readability. They create long lines so that developer needs to scroll in order to read the entire comment. The only exception is for variable declaration:

int itemCount = 0; // Number of items in the cart.

Provide description of a class and method interface in the comments. Explain what the purpose of the class or method is. Describe method arguments and return value. List exceptions it throws. Visual Studio has a nice feature that automates this process. If the class or method interface already exists then positioning the cursor just above it and typing “///” will auto generate comment section that developer needs to fill out.

/// <summary>
/// </summary>
/// <param name="customerNumber" />
/// <returns></returns>
public string GetBillPayAccount(int customerNumber)

The comment section will be part of xml documentation when generated. The documentation is also used by the intelisense. Therefore, it is beneficial to provide it with the accompanying assembly. Documentation generation is a project option. It is disabled by default. To enable it, right click on the project, choose properties, then select “Build” tab. At the bottom in the “Output” section check the checkbox “XML documentation file” and in the text box to the right of it enter the documentation file name.

Conclusion
The quantity of comments matters. Too many comments are as bad as not enough comments. Finding the optimum is imperative. We should not forget that quality of comments is critical. They should provide useful information. I would like to conclude with an important point worth noting. In most cases it is even worth sacrificing application performance for code maintainability.
Next week
In the next week post “Intellisense in Visual Studio” I will show how to enable intelisense for custom built libraries in Visual Studio.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.