Created
July 28, 2011 18:41
-
-
Save zerowidth/1112220 to your computer and use it in GitHub Desktop.
short circuiting and side effects
This file contains 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
# as suggested by @mcmire, https://twitter.com/mcmire/status/96632723220869120 | |
# and clarified in https://twitter.com/mcmire/status/96647536521129985 | |
class Array | |
def thoroughly_all?(&block) | |
all_true = true | |
each {|obj| all_true &= yield(obj) } | |
all_true | |
end | |
end | |
if models.thoroughly_all? { |m| m.valid? } | |
# ... do stuff | |
end | |
# I argue that this is not a good idea, because: | |
# | |
# 1. It extends core classes unnecessarily, which can be ok, but: | |
# 2. It relies on implicit (and potentially unclear) side effects. | |
# Without looking through the codebase to find out what "thoroughly_all?" is, | |
# it's not immediately obvious what's going on. | |
# | |
# In my opinion, it's much better to be explicit, even if it's a bit more code: | |
# validate everything explicitly | |
models.map { |m| m.valid? } | |
# then act on the results | |
if models.all? { |m| m.errors.empty? } | |
# ... | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment