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:
Bottom line:
Explaining yourself is good, not needing to do so is better.