If vs. Unless

October 31, 2011 § Leave a comment

unless is if’s negative brother. He crops up fairly often, particularly in one-liners, and almost always ruins my mood. if is a positive, can-do guy. unless is full of mistrust.

Every if has an else. Even those in one-liners. When you write:

puts "BACON" if Today.bacon_day

Ruby executes something like:

if Today.bacon_day?
 puts "BACON"

unless, as the oposite of if, also has an else. You write:

  puts "BACON" unless Today.bacon_day?

Ruby executes something like:

if Today.bacon_day?
  puts "BACON" 

I put it to you that, in most cases, that is crazy talk. Trying to mentally process that has taken me ages, and I’m still not convinced I’m right. unless has sent me into a spiral of doubt and uncertainty. I just wanted to know if I should print out “BACON”. Now I think I need counciling.

Of course, sometimes unless really is the guy for the job. However, I’d encourage you to explore the flipside of that unless and see if an if dosen’t actually better explain your intent.

Some smart people have thought on this. John Nunemaker makes some valid use-cases for unless, and the 37Signals guys get into a really obtuse example.

Leave a comment unless you don’t disagree ;)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

What’s this?

You are currently reading If vs. Unless at Logical Friday.



Get every new post delivered to your Inbox.

%d bloggers like this: