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" else nil end
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? nil else puts "BACON" end
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 ;)