I used to be a comment minimalist. But the more I return to my code, the more I’m tending to add comments. To explain how far I’m moving it would be worth describing some end points:
Bad
Comments that just repeat what the method name does:
# Add one to number
def add_one_to(number)
number += 1
end
That comment adds absolutely no value - and is just some additional content that needs to be managed. If a method definition explains the functionality then you should not add comments. Only add comments if they add value.
In fact I would go further than that - writing methods so that they self-document is good practice. In my book, the above is bad, but this is worse:
# Add one to number
def aot(n)
f(n, 1)
end
Comments should only ever be a clarification - they should never be the only explanation of the functionality. If you have to comment for people to be understand what your code is doing, then you need to rethink the way you code.
Good
The one file that I almost always add comments to (and one I think is too often not commented) is Gemfile. The main issue is that it is not always clear from the name of a gem, what functionality that gem is adding. The occasion that brought this home to me was when I was trying to track down where some database functionality was coming from. The functionality was added by the texticle gem, but it took me a lot of time checking through the READMEs of other gems before I worked it out. So now, if the name doesn’t obviously describe what the gems does, I will added a comment describing the gems functionality and/or why it’s been added to the app.
Another place I will always comment is where I have taken an unusual decision in the way I code. For example, because of an obscure bug I have had to handle an object in an unusual way. Such things should always be commented.
Inbetween
Recently I’ve started to comment classes. That is, I’ll add a comment to the class object describing what it does. It can often be difficult to choose a concise class name that fully describes what the object does and/or its place in the application. It is easier at the method level because what a method does is so much more limited. But a class is that little more complicated and therefore, that little more difficult to describe just by it’s name.