Categories
Ruby Uncategorized

Comments aren’t always evil

I tend to agree that comments are, in most cases, evil (or at least mildly malevolent), but I did come across one of the exceptions to the rule today.

While doing a bit of drive-by refactoring while fixing a bug, I reflexively changed this line:

unless instance_response.nil?

to this:

if instance_response

Then reading the comment above the line, expecting to delete it, it all came flooding back:

# Use instance_response.nil? to check if the HTTParty
# response's inner hash is empty.
# If you use 'if instance_response', it is always true.

Now you could maybe argue that this unexpected behaviour is because httparty uses just a little too much of that old method missing proxy magic (which of course isn’t really magic at all), but that’s not the point of this post.

In the end I pulled it out into a private method to make it clearer what was going on, but decided to leave the comment in.

def self.instance_returned? instance_response
  # Use instance_response.nil? to check if the HTTParty
  # response's inner hash is empty.
  # If you use 'if instance_response', it is always true.
  !instance_response.nil?
end

4 replies on “Comments aren’t always evil”

So shortly after posting about the evilness of code comments, comments on your blog stop working? Interesting…

Anyway, why are comments evil?
(Your link leads to a 1 hr podcast… )

Sure, they can be overused – but they can also be very useful and important.

Even Python code (*bait*) isn’t always obvious enough to not require explanatory comments.

As a general rule of thumb, I think the code explains the *what* while comments explain the *why*.

I’d rather have too much commenting than too little.

Obviously ‘evil’ is, as ever, an exaggeration, but comments should be a last resort. Much better to make the intention clear by, for example, extracting a local variable or provate method and giving it a meaningful name. Obviously there are some cases where comments are useful, but I like to only put them in when I can’t think of a way of clarifying things in the code itself.

The insidious thing about unnecessary comments is that they tend to go out-of-date. People change the code, but leave the comments, so they end up describing behaviour that’s no longer there, or they get separated from the code they were supposed to describe.

You could use a method whose name explains what the line of code does but it would probably be reflexively inlined by someone who sees it later anyway.

Thanks Kerry.
I actually agree with that description. So I guess it’s just the “comments are evil” rallying cry being a bit too misleading…

Leave a Reply