Last active
December 12, 2015 06:59
-
-
Save MichaelXavier/4733316 to your computer and use it in GitHub Desktop.
aborting a composed method early on failure
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
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
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.