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