When it’s it appropriate to comment code?
I follow a simple set of rules:
- If the code is confusing – I try to refactor the code so that it’s not confusing anymore.
- If a refactoring is not possible, I document the “why”, not the “how”. The “how” is already documented: that’s the code.
The “why” explains WHY the code exists and perhaps some important and relevant details that might not be evident to future maintainers.
How do I know if I should provide a “why”?
I ask myself this question:
In six months will I be able to understand this code in 30 seconds?
If there is any doubt in my mind then I know that I need to provide a comment for that chunk of code.
Why 30 seconds?
The majority of my time as a developer will be spent reading and deciphering existing code. I need to be able to do this as quickly as possible to be efficient. If a comment helps me grok something quickly due to some weird edge-case complexity, then the comment is worth its weight in gold.