Ok, maybe hate is a strong word, but I generally try to avoid commenting my code. Why?
I want to try to make the code I write understandable and read like well written prose. Does all of my code look like that? No, but I wish it did.
If I feel a line of code needs a comment, then I feel it’s better to extract that line into a function that will describe what it’s doing rather than adding a comment. This is my preference and I will admit that. I don’t say everyone else must code this way, but it is what I prefer. So let’s look at an example.
Let’s say I felt the need to comment the If statement following the loop with something like:
I would rather pull this out into it’s own function to make it clear what it does rather than add the comment:
I feel that then my final line of main code is more descriptive and I am able to debug it more easily and understand what it’s doing better when I return 12 months later:
The main problems I find with comments is:
- They don’t age well. If i change the code, I rarely change a comment related to it. Then it’s no longer helpful, it’s a misdirecting lie.
- Putting the descriptions in the variable and function names makes the code more readable and understandable and is a better code practice, in my opinion.
- Anything a comment can keep track of (like logging changes) is usually better tracked in a version control system with good log messages to encapsulate the overall purpose of changes.
So, I don’t want to remember to maintain my comments or have to update them when I make code changes. Again, I won’t rail against you if you use comments. I just don’t typically find them all that helpful. I’d prefer the code that is going to be compiled and executed to be telling me what it’s doing.