An unexpected controversy was born in a simple code review.
The most senior and respected developer on the team, known for his ability to fix the hardest coding problems (we’ll call him “The Fixer”) insisted that developers should never use comments in their code! His argument was that code should be clear and self-documenting, and if the code was well-written, comments are unnecessary.
After considering the arguments from both sides, as well as my own experience as a software development professional, I came to the conclusion that there is only ONE GOOD REASON to use comments in code. But before we get to that one reason, it might be helpful to look at various BAD reasons or uses for code comments:
- Restating what the code says
- Explaining bad code
- Stating the obvious
And this is only a small sample of how comments are so often misused.
So in what circumstances is the use of code comments good?
- Explaining why a specific coding choice was made
- Summarizing a large section of code
- Describing the business rules that the code must satisfy
- Reminders to complete future work that might not be feasible currently
Of course, none of these reasons should be used to compensate for bad or unclear code. If the code is bad, rewrite it; don’t comment it.
“But wait,” you might be thinking, “didn’t you say there was only ONE good reason for code comments? And now you’ve listed four reasons?”
Although it may look that way, if you look at the list of circumstances I’ve provided, you’ll notice they have one thing in common — and it is the one thing that can’t be directly and clearly communicated by the code itself:
In all of the examples, the purpose of the comment is to communicate INTENT. While the code itself provides the “what” and the “how,” it can’t communicate the “why.”
Therefore, the only good reason for reason for code comments: to communicate intent. When you are tempted to add a comment to your code, you should ask yourself: is there a way to communicate this idea, concept, or information through the code itself?
That’s my two cents…