ruby-style-guide
ruby-style-guide copied to clipboard
assignment in conditional ternary
Should assignment in conditional ternary be avoided ?
something like this
condition ? self.foo = bar : self.foo2 = bar2
it's dealing with operator precedence and it is less clear than
if condition
self.foo = bar
else
self.foo2 = bar2
end
that we are modifying some state
Conditional ternary should be used when the operations after the if or else statements are simple enough to be put into one line. The assignment operation is one of the simplest operations so it seems natural to use the simplified conditional in Ruby instead of a classic if/else.
Interesting question. I think @khmariem is right in principle, but in practice I don't think I've seen many assignments in ternary ops. I'd love to hear what others think about this or get some data from real-life usages in projects.
As someone who recently encountered basically this exact example, my opinion is that assignments should stay out of ternary, mainly because of humans difficulty in parsing statements effectively - I feel there are too many chances to misunderstand what the statement is trying to communicate.
There is this https://github.com/rubocop-hq/ruby-style-guide#nested-ternary-operators
Use one expression per branch in a ternary operator
Is it sufficient to clarify that an "expression" should not have side effects? (see https://en.wikipedia.org/wiki/Expression_(computer_science)#Side_effects_and_elimination) However, such wording would restrict the use of method calls in branches, as methods can have side effects as well.
Frankly, I'm puzzled to tell if foo(bar) falls into "one expression" category or not.
Assignment in ternaries should definitely be avoided if they are assigning to the same variable, eg
condition ? self.foo = bar : self.foo = bar2
vs
self.foo = condition ? bar : bar2