When I was first learning to program I was taught that you must comment your code. All good programmers provide nice descriptive comments for everything they write. If you don't comment your code, you're a horrible person.
I took this to heart and heavily commented my code. However, as time went by I noticed some problems with this approach.
First, it was a lot of work to write and maintain all of these comments. Often times I'd run into a comment that wasn't accurate - presumably the code had changed but the comment was never updated.
Additionally, comments were contributing a lot of extra noise to my source code. Just looking at a file with a large number of comments made my brain tired before I even started digging in to the contents.
Comments were inconsistent and marginally useful at best.
Clean code will set you free
Shortly after this I found the teachings of the great and wise Uncle Bob Martin. In his excellent book Clean Code: A Handbook of Agile Software Craftsmanship there is an entire chapter dedicated to the subject of comments. The first paragraph of this chapter seemed to exactly sum up my thoughts on comments:
Nothing can clutter up a module more than frivolous dogmatic comments. Nothing can be quite so damaging as an old crufty comment that propagates lies and misinformation.
He goes on to say that comments are typically used to clarify poorly written code. In most cases you should be able to restructure your code to be cleaner so the intent or logic is clear without comments.
After reading this my mindset completely shifted. It's simple - write clean code and you don't need comments. If you find yourself writing a comment then you have failed.
I got to a point where I basically never commented my code. This wouldn't be a problem if my code was always 100% clear, but of course it isn't.
Recently I was in a hand-off meeting with a client where I was going over some code we had written for them. Everything was going fine until I came upon a particularly complicated little piece of code.
It had been a few months since I had written this so it wasn't terribly fresh in my mind. Even though I knew generally what the code was doing, it wasn't clear exactly how it worked. I had to fumble my way through the code, basically re-learning what exactly was going on. The client asked me:
Is there a reason you didn't comment this code at all?
Of course I didn't have a good answer.
Somewhere in between
It has become clear to me that at times, comments are necessary. And this is exactly what the Clean Code book said all along. Although "nothing can be quite so helpful as a well-placed comment", they are at best a "necessary evil".
Indeed you should avoid comments whenever possible. Refactor and restructure your code to make it as understandable as you can. But then recognize when a comment is necessary - when the code is not expressive enough to clearly describe what is going on.