Recently I’ve started to notice that the majority of comments I write are either redundant, or are excuses for other failings in my code.
Since that realisation, I’ve been making a conscious effort to eliminate the majority of comments from the code I write.
I find that comments generally fall into a handful of common categories. Here’s how I’ve been dealing with each:
I often find myself using a comment, when extracting code to a method would be better.
I find this much easier to read:
Now I don’t need to understand how free shipping is applied, only that it is applied when this condition is satisfied.
if statements like this a lot:
That first line conflates two concerns; whether a payment is due, and what to do when it is.
Moving the predicate in to a new variable, with an appropriate name, makes the code easier to read and eliminates the need for the comment:
This most commonly occurs when I’m declaring a variable, then using it some time later.
If that variable is poorly named, I’ll instinctively write a comment explaining what code that uses it is doing.
This is simply fixed by using more descriptive names in the first place:
I usually add these comments when I’m writing code that isn’t fully-formed in my head yet.
I have some idea what I need the code to do, so I write the first thing that does the job.
This kind of code is often accompanied by a comment that explains what the code does, rather than why it does it.
What I should do is go back and refactor the code to make it self-documenting, making the comment un-necessary.
These comments are probably the only ones I’m going to keep writing.
Sometimes, I come to code I’ve written a while ago and have no idea why it is written in such a strange way.
Often, it’s because I’ve profiled it and found it to be significantly faster, or because it catches an edge-case that a more intuitive method of doing the same thing might not:
Comments like this get to stay.
The majority of comments I write are a born out of lazy coding, and can be eliminated by simply naming things better or adding more abstraction.
I’m find that when I focus on removing the majority of comments from my code, it actually becomes more readable. The exception is comments that explain why, not how.
Let me know if you’ve found the same thing!