A silly Ruby coding error

16 Sep 2013

I spent a while tracing through some of my code the other day and discovered a bug I had introduced. I had a function that consisted of a series of conditionals like this:

class Bar
  def foo?
    is_foobared? &&
    was_small?
    has_transmogrified_explaination? &&
    fizzled?
  end
end

But as you can see, I accidentally removed the logical AND operator on the second condition. When the method was invoked, the interpreter would evaluate the first expression, ignore the result, and then evaluate the second expression and return the result.

One way to avoid this is to put the logical AND operator at the beginning of the line. This makes it easier to see if an operator is missing, and it's syntactically invalid unless you use line continuation characters:

class Bar
  def foo?
    is_foobared? \
    && was_small? \
    && has_transmogrified_explaination? \
    && fizzled?
  end
end

Kind of ugly with those line continuation characters. And formatting code to fit vertical boundaries feels kind of weird; I remember reading something by someone famous (I want to say that it was Steve McConnell in Code Complete, but maybe he was recommending the exact opposite) where he recommended not doing that because you might do something like this:

foo  = 42
bar  = 43
buzz = 44

And then you have to add a declaration for fiddlesticks and you have to redo your formatting.