Spot any errors? let me know, but Unleash your pedant politely please.

Sunday, 22 February 2009

What I think about comments.

Some people tell you that you don't need comments. It may be true for them, but it's not true for everyone. So unless you keep your code to yourself, you need to use comments. You shouldn't state the obvious. This is a bad comment:

   # increment the loop variable
   i++;


Comments are more useful to remind yourself why you did something in a certain way. Comments shouldn't really explain what the code does, they should justify or clarify something about the code. It's better to have comments on blocks rather than lines. It's OK to add comments to help when learning a language or technique that you maybe will strip out later.

Example of a good/useful comment :

       // create and populate the first few
       // rows. Shouldn't really have to,
       // but if we don't, autosize will
       // throw a wobbler later on
       //
    HSSFRow row = null;
    HSSFCell cell = null;
    for (int rowNum = 0; rowNum < dataRow; rowNum++)
    {
       row = worksheet.createRow(rowNum);

       for (int col=0; col<headersText.length ; col++)
       {
          cell = row.createCell((col + 1), cellType);
          cell.setCellValue("");
       }
    }

It's a good comment because it's going to explain why some odd code is in there, and it'll stop someone taking it out in the future and having to go through the pain of finding a workaround for a problem that they'd inadvertently reintroduced.

It's also formatted in an unusual way. It spans multiple lines, and it's over-indented. This is very deliberate. It stems from the days before syntax-colouring. It achieves two things. The comments get out of the way when you're reading the code, and the comments stand out when you want to read the comments. I've been doing this for years. An old boss used to do it and it infuriated me. He explained why he did it though, and persuaded me to try it for a while, and it works. It's a great way to format comments.

No comments:

Post a Comment