Skip to content

Instantly share code, notes, and snippets.

@zerowidth
Created July 28, 2011 18:41
Show Gist options
  • Save zerowidth/1112220 to your computer and use it in GitHub Desktop.
Save zerowidth/1112220 to your computer and use it in GitHub Desktop.
short circuiting and side effects
# 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