Cargo-cult commenting

Currently I am responsible for maintaining a big legacy .NET ERP system. It’s plagued by something I like to call cargo-cult commenting — source code comments that are ritually included, for some reason, but serve no real purpose at all. These are the sort of comments that:

  • Are written for aesthetic reasons more than anything else
  • Usually just repeat the next line of C# in sentence form
  • Tell you what the code does, not the reasons why
  • Don’t add any value whatsoever
  • Just make the code base even more bloated and crappy than it was before

Here are a few examples to demonstrate exactly what I mean.

/// <summary>
/// POST
/// </summary>
/// <param name="oSpace"></param>
public override void POST(ref Space oSpace)
//Create a new attribute.
XmlAttribute newAttr = xmlDocuments.CreateAttribute("Directory");
newAttr.Value = "CompanyCorrespondenceDocs";
// read-only?
if (bVehicleEdit == false) oField.SetReadWrite(ref oSpace, true);
// return the vehicle risk
return DataAccess.ExecuteXml("Result", "Row", "Vehicle_VehicleRisk_Get", 
    iVehicleID).SelectSingleNode("Result/Row");

This sort of rubbish gets in the system because people are taught the stupid rule that comments are always good, no matter what their purpose is. One developer sees another developer writing a line of comments for every 2-3 lines of code, copies it, and pretty soon sections without any green look naked and unfinished. If only unit tests were written like this!

Anyway, my golden rules for code commenting are:

  1. There are only two valid reasons for writing comments — to explain why code was written (e.g. original business motivation), or as a warning when something unexpected happens (here be dragons).
  2. Write the reasons why something is done, not how.
  3. If you find yourself putting comments around little blocks of 3-6 lines of related code, each of these blocks should probably be a separate method with a descriptive name instead.
  4. If you can’t write anything useful (i.e. that couldn’t be determined by a quick glance at the code), don’t write anything at all.
  5. BUT if you find yourself regularly needing to write comments because it is not clear what’s going on from the code, then your code probably isn’t expressive enough.

Writing good comments is hard. One habit I’ve recently adopted is to paste entire paragraphs of relevant user requirement into my code to explain why it was written. It’s working really well — it saves me time, and produces comments of very high quality, straight from the horse’s mouth. I encourage you to try it too.

January 13, 2009

1 Comment

jbland on January 14, 2009 at 1:30 pm.

in college there was a CS professor who literally made his students comment every single non-blank line of code. The only things that werent commented were comments. i can see the spirit, but more often than not the comments got “creative”

Leave a Reply