Discussions about commenting code can be surprisingly heated. Some will say that good code should explain itself, and needs no comments. Others will insist on the need for comments without actually approaching any discussion of how to distinguish good from bad comments.
Bad comments are easy enough to recognize. Many simply repeat in plain language what the code is doing. The worst may actually explain the reasoning behind the code, but do so incorrectly. For the most part, bad comments will make you ask why they bothered, as they are pointless additions, and simply increase the noise level in the module.
What makes a good comment? The title of this article is a hint, but may be better understood if I write why comments. The idea here is that the value of a comment is proportional to any insight or motivation it can explain. A good comment explains why the code is needed, and all too often that may be far from obvious.
Applications are increasingly complex in their use, and many of them serve the needs of specialized problem domains. Any specialty area of knowledge and practice will have operations which those experienced in the domain may take for granted, but which are not obvious to someone new to the field.
It is helpful to keep in mind a Martin Fowler quote: “Any fool can write code that a computer can understand. Good programmers write code that humans can understand.”
So a why comment is one which provides understanding to programmers who did not write that code. Most applications contain very little of such useful commentary.
Yes! The code should be self-explaining in that it should be easy to see WHAT the code does. However WHY the code does things is something you should write in a comment.
And WHY you CHANGED the code is something to be found in the comment of the commit.
I totally second that.
I comment a lot, not what the code does but why I took the design decision.
On long term projects, sometimes you have to go back 10-15 years and your mindset is different. You evolved, you learned a lot in the meantime, your programming skills have changed and improved. Comments allow me to come back to what I was thinking at the time and have a clear picture instead of spending days wondering why the heck I did it this way instead of another one. Comments is a guarantee for the future where you’ll know which tools and configurations you were using at the time of coding, and how you were thinking at the time.
Priceless.