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
@jakeonrails
Copy link

I think it depends on what your return value means in this context. If false means "The shop is out of widgets", then rescuing an exception to return false seems wrong.

If you are returning true/false to indicate whether a process was successful or not, then return false on error seems to make sense, although by catching the exception you make it hard for the caller to find out why the process failed.

I think the main logic behind not using exceptions for control flow is because you get some sort of a weird spaghetti code situation akin to using GOTO.

I don't think it's always bad though, especially if your exceptions/control flow are handled internally, as in your example.

@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