Last active
December 21, 2015 03:18
-
-
Save pbyrne/6240889 to your computer and use it in GitHub Desktop.
I'm building a small array dynamically and then picking the maximum value. I have problems with each formulation. Which choice is less evil?
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
# This option has the most clarity, but I generally hate local variables in a | |
# method, preferring to use tap. | |
def calculated_foo | |
available_foos = [] | |
available_foos << bar | |
available_foos << baz.qux if baz | |
available_foos.max | |
end | |
# It's a little less clear, unless you know what tap is, and `end.max` is | |
# painful to look at. | |
def calculated_foo | |
[].tap do |available_foos| | |
available_foos << bar | |
available_foos << baz.qux if baz | |
end.max | |
end | |
# This avoids the painful `end.max` for a more-common `}.max`, but goes against | |
# the culture of using do/end for multi-line blocks. | |
def calculated_foo | |
[].tap { |available_foos| | |
available_foos << bar | |
available_foos << baz.qux if baz | |
}.max | |
end | |
[bar, baz ? baz.qux : 0].max
Because my code is for the right ppl only, knowhadimean?
Oh, and I fail in the presence of negative numbers because I'm too cool to care.
But if you're one of those guys who actually want their code to be readable, then may I suggest something completely different:
def good_method_name_that_exposes_intent
return bar unless baz
[bar, baz.qux].max
end
function calculatedFoo() {
return Math.max.apply(Math, [bar, baz ? baz.qux : 0])
}
module NullObj
def self.qux;0;end
end
[bar, (baz || NullObj).qux].max
i personally would just pick one of your options and go (problem the first one with the local), but i figured i'd add something to the discussion.
[bar, baz ? baz.qux : nil].compact.max
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://gist.github.com/jphenow/6240939