Other people's code

I'm currently working on a 10+ year old code base and often come across some code that I am initially baffled by.

def using_custom_theme?
  !custom_theme_id.nil?
end

My first thoughts were - why ? This is the sort of logic kungfu that really hurts my brain. Why not just use .present? ?

Actually my first thoughts were - why not just use custom_theme_id - the only falsey value you can get is if it's nil... but perhaps the author really wanted a true or false return. So why not just use !!custom_theme_id ?

I guess that doesn't read as fluently as .present?

I did wonder if .present? just wasn't around when this application was first created but it looks like it's been there since 2008 - predating this by a number of years.

I did take a look at the implementation of .present? to see if there were good reasons to use the double bang !! - maybe there is a clear performance difference. However, the implementation of .present? is satisfyingly simple -

  def present?
    !blank?
  end

The blank method has a simple test for supporting string and array presence (0r any other class that responds to empty?) -

  def blank?
    respond_to?(:empty?) ? empty? : !self
  end

These aside, .present?, when you squash it down is actually just doing a double bang.

So, there is a performance difference - an additional method call and a condition testing the empty? method exists - but there are few real world situations where this is ever going to be a concern.

Here's to using .present? with aplomb!

Subscribe to Useful Stuff

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
jamie@example.com
Subscribe