If the code and the comments disagree, then both are probably wrong

Let us change our traditional attitude to the construction of programs. Instead of imagining that our main task is to instruct a computer what to do, let us concentrate rather on explaining to human beings what we want a computer to do.
— Donald Knuth

I recently wrote some code commenting guidelines to explain why comments are usually a Good Thing. Some intelligent and good looking people agreed with me, while others insisted sharing incoherent and rambling opinions.

Mads Kristensen rightly pointed out that, “If [comments] are good, then the code is also good”. Some people took this to mean that if a piece of code has good comments, then it’s also guaranteed to be of the very finest quality. There’ll always be exceptions. Code with good comments can easily be mutilated by a placement student or twisted beyond sanity by a crazed Perl developer. But good comments are often correlated with good code when the software is built by a good developer.

How about this one, “code should be written in a way that doesn’t require commenting”. Close, but wrong. Code should be written is such a way that it doesn’t require commenting to explain how it works. My original article wasn’t about refactoring, but if you have a block of code with a comment then sometimes it makes sense to extract it into its own method. If it still isn’t clear then try renaming the method. If you think you need a comment to note assumptions then state them explicitly by introducing an assertion. If there’s still any uncertainty then use comments. Explain obscure optimizations or special algorithms. Explain why you’re code does what it does.

Posted in .net. 3 Comments »

3 Responses to “If the code and the comments disagree, then both are probably wrong”

  1. Coding Guidelines - Commenting « Charismatic Megafauna Says:

    [...] If the code and the comments disagree, then both are probably wrong [...]

  2. Will Asrari Says:

    Receiving a well-prepared spec-sheet is usually enough to explain why code was written the way it was written. Those are always available and developers need to read those before being thrown at a project.

  3. Will Asrari Says:

    I’m glad I was at least close in the last article but I honestly feel that there is no real right or wrong answer when it comes to commenting code.


Leave a Reply