back

Ruby tip: Return early

This tip has been covered in Refactoring, as well as a few other places, but I still see it pretty regularly go unused in rails code.

Tip: Instead of nesting, just return early.

E.g.

1
2
3
4
5
6
7

def go_home
  if wants_to_go_home?
    pack_bags!
  end
end 

While this code is fine, it’s both clearer and more concise to say:

1
2
3
4
5
6

def go_home
  return unless wants_to_go_home?
  pack_bags!
end

Update:

‘xyz’ points out in a comment that this is a horrible example of when to use this as it’s far better to just say:

1
2
3
4
5

def go_home
  pack_bags! if wants_to_go_home?
end

While my intention had been to give a short example, it would probably have been better to give something like:

1
2
3
4
5
6
7
def go_home
  if can_go_home? && wants_to_go_home?
     pack_bags!
     get_tickets!
     board_plane!
  end
end

In this case, I think it becomes worthwhile to instead do:

1
2
3
4
5
6
def go_home
  return unless can_go_home? && wants_to_go_home?
  pack_bags!
  get_tickets!
  board_plane!
end

Hopefully that is a better example!

February 09, 2009

  1. xyz says:

    If clarity is the objective, why not just:

    1
    2
    3
    
    def go_home
      pack_bags! if wants_to_go_home?
    end
    

  2. Rymaï says:

    My first thought was "it's not so clear", but now, I've tried it and I like the way explicitly calling "return" to say "get out of here!". ;)

    Thanks for the tip, I had seen it before, but never really used.