Skip to content

Instantly share code, notes, and snippets.

@MichaelXavier
Last active December 12, 2015 06:59
Show Gist options
  • Save MichaelXavier/4733316 to your computer and use it in GitHub Desktop.
Save MichaelXavier/4733316 to your computer and use it in GitHub Desktop.
aborting a composed method early on failure
# is this the best way to do it?
# in this way, each method must raise if something goes wrong,
# but this behavior isn't necessarily exceptional. composed_method
# uses this exception for control flow because its contract is that
# it returns true on success, false on failure.
# I've cargo culted the phrase "don't use exceptions for control flow" but I realize I don't know why...
def composed_method
frobulate_widgets
refrobulate_widgets
confribulate_frobulations
true
rescue FrobulationError
false
end
@arikfr
Copy link

arikfr commented Feb 10, 2013

It's hard to discuss it on such a high level example, but how about:

def composed_method
  frobulate_widgets && refrobulate_widgets && confribulate_frobulations
end

Assuming that each of them returns boolean value, in case one of them fails it won't proceed to the next and return false as expected. Otherwise it will return true.

If the assumption doesn't hold (some of them don't return boolean value) you can wrap them.

But at the end of the day, "it depends". In some cases the pattern you showed (to rescue an exception) will be acceptable too.

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