Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

assignment in conditional ternary #704

Open
MathieuDerelle opened this issue Feb 16, 2018 · 5 comments
Open

assignment in conditional ternary #704

MathieuDerelle opened this issue Feb 16, 2018 · 5 comments
Labels

Comments

@MathieuDerelle
Copy link

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

@khmariem
Copy link

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.

@bbatsov
Copy link
Collaborator

bbatsov commented Jun 12, 2019

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.

@pnomolos
Copy link

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.

@pirj
Copy link
Member

pirj commented Feb 22, 2021

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.

@sumirolabs
Copy link

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

6 participants