Programming Practices – Issues with Comments Explaining Complex Code

commentsdocumentationprogramming practices

A lot of people claim that "comments should explain 'why', but not 'how'". Others say that "code should be self-documenting" and comments should be scarce. Robert C. Martin claims that (rephrased to my own words) often "comments are apologies for badly written code".

My question is the following:

What's wrong with explaining a complex algorithm or a long and convoluted piece of code with a descriptive comment?

This way, instead of other developers (including yourself) having to read the entire algorithm line by line to figure out what it does, they can just read the friendly descriptive comment you wrote in plain English.

English is 'designed' to be easily understood by humans. Java, Ruby or Perl, however, have been designed to balance human-readability and computer-readability, thus compromising the human-readability of the text. A human can understand a piece of English much faster that he/she can understand a piece of code with the same meaning (as long as the operation isn't trivial).

So after writing a complex piece of code written in a partly human-readable programming language, why not add a descriptive and concise comment explaining the operation of the code in friendly and understandable English?

Some will say "code shouldn't be hard to understand", "make functions small", "use descriptive names", "don't write spaghetti code".

But we all know that's not enough. These are mere guidelines – important and useful ones – but they do not change the fact that some algorithms are complex. And therefore are hard to understand when reading them line by line.

Is it really that bad to explain a complex algorithm with a few lines of comments about it's general operation? What's wrong with explaining complicated code with a comment?

Best Answer

In layman's terms:

  • There's nothing wrong with comments per se. What's wrong is writing code that needs those kind of comments, or assuming that it's OK to write convoluted code as long as you explain it friendly in plain English.
  • Comments don't update themselves automatically when you change the code. That's why often times comments are not in sync with code.
  • Comments don't make code easier to test.
  • Apologizing is not bad. What you did that requires apologizing for (writing code that isn't easily understandable) is bad.
  • A programmer that is capable of writing simple code to solve a complex problem is better than one that writes complex code and then writes a long comment explaining what his code does.

Bottom line:

Explaining yourself is good, not needing to do so is better.