Code comments should help you and other developers understand the code. Or “why project code standards can result in unwanted behaviors”

The purpose of commenting your code is to help you and other developers that come after you to understand the code. If a code comment doesn’t offer anything in addition to the code itself then it’s pointless and just adds noise.

Method and variable naming is also important, a descriptive method name shouldn’t need copious additional inline comments if it already describes what it does. Obviously you don’t want the extreme and have a method name that’s hundreds of characters long. Be sensible.

I often come back to these 2 Twitter posts that illustrate how inline comments that state the obvious are useless:

Another one making the same point:

There’s many reasons why developer’s comments add little value. The main reason is probably just not putting in the effort and time to write something that’s useful. There’s another reason though that leads to documentation that looks exactly like this:

/**
 * This method retrieves an Account.
 * @param accountId the account id
 * @return the Account
 */
public Account retrieveAccountById(String accountId){
    // code here
}

First, the name of the method, the parameter and the return type tell you a lot about the purpose of this method. So why would anyone take the time to write “This method retrieves an Account” that clearly just repeats what the code already says?

Have you ever seen statements like these:

  • Every Class must have JavaDoc that describes the Class
  • Every method must have JavaDoc that describes the method and it’s parameters

This is an example where standards encourage unexpected or unwanted behaviors. The intent of both of these statements is good. In most cases it is beneficial to have documentation that helps others understand what the code is and what is does. There is a point however that if you’ve named your method, it’s parameters and it’s return clear enough, there isn’t anything left to say in the documentation for the method.

“But the code standards say we must write JavaDocs, so I have to write something!”

Standards and rules are established for a purpose, but they have to add value. Be flexible. If something doesn’t add value, you shouldn’t follow it blindly. Do what makes sense.