Skip to content

Instantly share code, notes, and snippets.

@naush
Created March 12, 2012 00:45
Show Gist options
  • Save naush/2018923 to your computer and use it in GitHub Desktop.
Save naush/2018923 to your computer and use it in GitHub Desktop.
# multiple exits
if a
code
code
code
if b
code
code
code
return c
else
code
code
code
return d
end
else
code
code
code
return e
end
# single exit
result = nil
if a
code
code
code
if b
code
code
code
result = c
else
code
code
code
result = d
end
else
code
code
code
result = e
end
return result
@JoshCheek
Copy link

edit: this comment was in response to original gist.


I'd probably write it like this:

return e unless a
code
code
b ? c : d

If c, b, and d were long, I'd write

return e unless a
code
code
return c if b
d

And I suppose in reality, I'd probably extract some methods out of there (if not possible, then I might extract a class).

@naush
Copy link
Author

naush commented Mar 12, 2012

I mean we can refactor either approach to be reasonably easy to follow, but then you're just comparing two pieces of beautifully crafted code. :)

I'm just saying, when I'm trying to follow other people's code that looks like some longwinded maze, I prefer it to have a single exit point.

@JoshCheek
Copy link

I'll accept that. Perhaps context is the differentiator here.

@naush
Copy link
Author

naush commented Mar 12, 2012

Context definitely plays a big role here. I can see how early returns can help in some situations, too. Steven's rewrite is a good example.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment