I have a best practices question about some code.
Which code is easier for another programmer to understand:
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
if rocks > pebbles | |
puts "You have more rocks than pebbles." | |
elsif rocks < pebbles | |
puts "You have more pebbles than rocks." | |
end | |
if rocks > pebbles | |
puts "You have more rocks than pebbles." | |
elsif pebbles > rocks | |
puts "You have more pebbles than rocks." | |
end |
Should I switch the greater_than and less_than signs [as in elsif in the first example (lines 1-5)] or should I switch the position of rocks and pebbles [as in the elsif in the second example(lines 7-11).] I prefer the second example because the puts statement is essentially the same as its if statement.
However, maybe it's easier for some people to think of the comparison in terms of, well, in this case, rocks. (I really don't know why.) What do you think?
1 comments:
I would go for ternary operator or logical composition with 'and' and 'or' for readability.
puts "#{rocks>pebbles and 'You have more rocks than pebbles.' or 'You have more pebbles than rocks.'}"
Or even make a method that takes three arguments, for readability and reusability.
What do you think?
Post a Comment