Blog: Working with Large Codebases > Documentation & Communication

Is your code poorly commented? Three indicators..


Thursday, July 8th, 2010 - By Vineet Sinha

One fact that is agreed upon – is that it takes a lot of time to understand code. Poorly commented code just makes this harder. The challenge that we face, is that developers’ often don’t want to take time away from coding to document, but working with code that is not commented takes more time in the long run.

It is always nice to work on a project that has excellent commenting. However, there have been many projects that I have worked on that have frustrated me with the effort needed in understanding them. When code that I have been writing needs to build on badly documented components, I have sometimes added my own comments. Tragically, I have often not been responsible for maintaining such components and my effort in commenting has gone to waste – as I have not checked them in. Such code often has had three traits.

1. When documentation in needed to understand what is going on.
Code sometimes is so cryptic that many lines of comments are needed to make sense of what is happening. If written well, this code would use clear variables and method names so that the logic is immediately obvious. Doing this not only helps in understanding what the code is doing, but also allows for comments to be used for describing why the code is needed (see item 3).

/**
* calculate the amount of interest gained from a principal of p at a
* rate of r over y years loop through each year and calculate the
* new amount based on the rate. set the principal to the new
* amount for interest compounded annually.
*/
public static float main(float p, float r, int y) {
  DecimalFormat format = new DecimalFormat( "0.00" );
  float a;
  for(int i=1;i<=y;i++){a=p*(1.0+r);}
  p=a;
  return format.format( a );
}

The lack of useful variable names and structure in this code prevents it from being easily read, necessitating the use of comments to describe what it does

2. When there is more comment header than actual useful comments.
In the quest for helping developers writing comments quickly, development tools often generate comment headers when creating new classes, methods, etc. While such headers can be helpful, leaving them as-is makes it harder for us to detect the signal (the actual useful comments) from the noise (the automatically generated headers). Instead filling in these headers can make understanding easier.

/**
* @param principal
* @param rate
* @param years
* @return compundedInterest
*/
public static float calcInterest(float principal, float rate, int years) {
  DecimalFormat precisionTwo = new DecimalFormat( "0.00" );
  float amount;
  for ( int year = 1; year <= years; year++ )
  {
    amount = principal * (1.0+rate);
    principal = amount;
  }
  return precisionTwo.format( amount );
}

Here we see how automatically generated headers become useless noise when left as is.

3. When it is not obvious why a piece of code behaves in a particular way.
One can always figure out what a piece of code is doing (although sometimes it can take a lot of effort). The challenge however, is that if not documented, it is impossible to figure out why the code needs to behave in the way that it does. When writing code, it is therefore important to ask yourself the ‘whys’ and to make sure that it is included in code comments.

/**
* Calculate compound interest for accounting form 2-a.
* We are calculating the interest by using a loop instead of
* principal*(1+rate)^years to show the exact workings of the compounded
* interest calculation
*/
public static float calcInterest(float principal, float rate, int years) {
  DecimalFormat precisionTwo = new DecimalFormat( "0.00" );
  float amount;
  for ( int year = 1; year <= years; year++ )
  {
    amount = principal * (1.0+rate);
    principal = amount;
  }
  return precisionTwo.format( amount );
}

An example of a quality comment describing why the code is needed and why it was written the way it was

Other resources
For other tips on improving comments and code quality see the following articles:

 

5 Comments 6 Tweets

14 Comments

  1. You can put comments in code???

    This comment was originally posted on Reddit

  2. colinhect says:

    // Increment i by one i++;

    This comment was originally posted on Reddit

  3. alephnil says:

    > Good comments are concise and accurately document behavior. Poor ones are not, and do not. That’s it. That is correct description, but not very useful as advice to inexperienced programmers. A newbie can write code like this: while(i < a) { …. } // end while loop And actually thinks that fits your criteria for good comments. The problem here of cause is that the comment just repeats what can read from the code anyway. In less obvious examples, the logic of the loop would be explained in a comment block above it. A good comment would describe more abstract and higher level concepts, that not necessarily can be read from the code.

    This comment was originally posted on Reddit

  4. StolenRecipe says:

    That documents language behavior, clearly covered elsewhere. I’d expect my developers to know what "documented behavior" means, and if they don’t, I’d tell them. Not rocket science.

    This comment was originally posted on Reddit

  5. oct says:

    If a code is too cryptic than it has to be refactored.

    The best code documentation is the code itself. This however doesn’t mean comments should be excluded, but they would be less important compared to code.

    • Vineet Sinha says:

      Great point.

      I actually spend more time refactoring than coding – it often just makes alot of sense.

      I was mainly thinking about bad comments with this post.

  6. I normally only really document the interface well, the .h file in C.

    This comment was originally posted on Reddit

  7. Stark says:

    I wouldn’t be too dogmatic about #2. If, for example, the method is abstract there will be no code, but the function should still be fully documented.

    #3 sounds like what you are supposed to do, except it never answers the “why” except in a circular way and there is no explanation for returning “precisionTwo.format( amount )” when the documentation implies that “amount” will be returned. I am assuming that the former *is not* the Java DecimalFormat format function which returns String not float.

    It is not commenting exactly, but the function names should tell as much about the function as it can in a reasonably concise way. e.g. compoundIntereset vs calcInterest

    • Vineet Sinha says:

      Good point, regarding abstract methods. But that definitely seems to be the exception to the rule. I have just see way too many times of people feeling it is their duty to just auto-generate headers.

      As for #3. Yes the argument feels circular, but I still feel that the main point is clear – it is hard to figure out the ‘why something is happening’ yourself while figuring out the ‘what is happening’ is definitely doable (especially if you have good naming).

      And also good point regarding function names. I actually think I should write a whole blog post on the issues regarding it soon.

  8. Rafael Forte says:

    I couldn’t have put it better. I also like to comment each “paragraph” of my code. It keeps things organized, separated, and it is a good way to introduce refactorings using extract methods if you like the approach described in Clean Code…
    Regards,
    Rafa

  9. [...] Les comités d’architectures, pour ou contre Ten Weaknesses of the Agile Methodology Is your code poorly commented? Three indicators… Generating Enterprise Class GWT applications for Spring 3 Web comic series every geek has to know [...]

  10. lardingd says:

    Feel the need to comment that the first example has a logical error (loop ends too early)…that example seems in opposition to your complaint about poor commenting. Actually this blog entry appears more about code style then comments. The 2nd entry is undersold. The auto-generated comment is not meant to describe, it’s meant as a basis for your description. Adding descriptions following the parameters, would have helped to show how pointless the auto generated head was, as there is nothing further to describe. Really the second example is about using coding style as an alternative to commenting. Also, the third example gives intricate details of the algorithm of a method as part of the description to a public method, which is often inappropriate. Method descriptions should tell what, not how. Also such algorithm descriptions can cause more pain then help when comments are not kept in sync with updating code, leading to confusion in older code.

    A more appropriate title would have been “Is your code poorly styled? Three ways comments indicate this”.

    Interesting read…

    • Vineet Sinha says:

      Thanks for your comment. Interesting read. I agree with each of your sub-points, but your points raise other interesting issues that are worth consideration and don’t make the main point less important. I have seen these three situations in numerous situations and really wanted to highlight them.

      Please continue discussion on the forum: link

Leave a Reply

Additional comments powered by BackType


[ bbPress synchronization by bobrik ]