Last week I had the good fortune of having my colleague Abdel Saleh go through some rspec specs I had written.

“Why do you need this comment?” he asked for a bit of code like this:

  
before(:all) do  
  # Ensure doesn't actually save to Mogile FS
  MogileFS::MogileFS.any_instance.stubs(:store_content)
end  

..and he promptly deleted it..

“No wait!” I said defensively, “That’s there to prevent the tests from actually hitting mogilefs. The comment’s there because the line of code doesn’t describe the intent”

“Well, that’s easily fixed” says Abdel, “Rather than using a comment to describe the intent, put it in a method with a name that describes the intent.”

  
before(:all) do  
  ensure_doesnt_save_to_mogile_fs
end

def ensure_doesnt_save_to_mogile_fs  
  MogileFS::MogileFS.any_instance.stubs(:store_content)
end  

Why is this better!??

Comments aren’t maintainable. They don’t grow and change with the codebase. They lay still and live on like strange messages from ancient civilisations.

In the preceding example you no longer NEED a comment to describe the intent of your code, your code does it for you!

Need to find a lawyer for your business? Get in touch with my company Lexoo and we'll find you a great one for free.