The truth speaks for itself!

Not just for Ruby this time. This applies to pretty much every programming language under the sun.

Don't use unnecessary control statements to determine whether you want to return true or false.

def foo
  if some_boolean && other_boolean
    return true
  else
    return false
  end
end

You should do this instead:

def foo
  return some_boolean && other_boolean
end

It's very very rare that I ever have to return an explicit true or false. This should be a warning sign.

Of course, in Ruby you don't need to return explicitly so you should do this:

def foo
  some_boolean && other_boolean
end

Leave feedback...

  1. So what is it warning you of when you see that?

    I could definitely see myself tempted to do it the first way, simply to make it really explicit what it’s doing, Why is that bad?

  2. Apart from being messy and requiring me to load 5 lines – 4 of which are fluff – into my brain to understand it, a benchmark on Ruby 1.8.6pl114 shows being really explicit (first example) takes about 138% of the time, and returning explicitly (second example) takes about 135% of the time that the cut-down version (third example) takes.

Commenting is closed for this article.

About the boy

A picture of Craig in grayscale

Craig Webster is a software engineer living in London. He usually works with Ruby although sometimes he sneaks in some Erlang or JavaScript. He's into rock climbing, snowboarding, skating, photography and fencing. Yes, this does mean he has a sword.

Near here you'll find Craig's homepage, contact details, PGP key and keysigning policy, and talks.

Licence

The entire content of this blog is public domain. Use it however you fancy. You don't even need to attribute it to me, although it would be nice if you did. Just don't sue me and we'll all be happy.

I Work With Rails

Recommend Me

My Travels

I go places. Do you go places too? Let's meet up!.