Assignments in conditionals (was: "if x == x = 1 || x = 2 || x = 3" WTF?!)

Slightly off topic:

Please don't hijack threads. When you change the subject, change the Subject.

does anyone else shy away from the following as potentially very confusing?

    if x = foo()
      bar(x)
      ...

I mean, you have to be looking quite hard indeed to tell it apart from:

    if x == foo()
      bar(y)
      ...

...which is a completely different thing. Altogether.

Yes, that is a longstanding controversy. I've seen such things in
forty year old C code, and have always preferred to do the assignment
first. Nowadays the usual advice, other than avoiding such constructs
if practical (it isn't always), is to wrap it in parentheses. This
will at least signal the reader that there's *something* going on
that's not entirely normal. And/or comment *why* you couldn't do the
assignment before the conditional.

-Dave

···

On Fri, Nov 11, 2016 at 8:49 AM, Andy Jones <Andy.Jones@jameshall.co.uk> wrote:

--
Dave Aronson, consulting software developer of Codosaur.us,
PullRequestRoulette.com, Blog.Codosaur.us, and Dare2XL.com.

This is controversial.

I personally prefer the assingment in conditional, because in this case I
value more the compact code that you get. It is very unlikely that I
confuse it in my or other's code.

Also, we totally use that idiom across the Rails code base.

Other people have other trade-offs. That is fine.

···

--
Sent from Gmail Mobile

Nice to see I'm not alone here.

Please don't hijack threads. When you change the subject, change the
Subject.

For the record, if I had considered it a genuine change of subject, I would have done just that. I thought it was a 50/50 call. I was after all talking about a much simplified case of the same thing -- reducto ad absurdum, perhaps.

Click here to view Company Information and Confidentiality Notice.<http://www.jameshall.co.uk/index.php/small-print/email-disclaimer&gt;

This is controversial.

I personally prefer the assingment in conditional, because in this case I
value more the compact code that you get. It is very unlikely that I confuse
it in my or other's code.

But you typically only reap reasonable gains in case of loop
conditions because then you can get rid of redundant code. In case of
plain if / unless that one more line is well invested IMO.

Also, we totally use that idiom across the Rails code base.

Oh.

Other people have other trade-offs. That is fine.

Phew. :wink:

Cheers

robert

···

On Fri, Nov 11, 2016 at 4:09 PM, Xavier Noria <fxn@hashref.com> wrote:

--
[guy, jim, charlie].each {|him| remember.him do |as, often| as.you_can
- without end}
http://blog.rubybestpractices.com/

So never run a Rails app with warnings enabled.

···

On 12/11/2016, Xavier Noria <fxn@hashref.com> wrote:

Also, we totally use that idiom across the Rails code base.

--
  Matthew Kerwin
  http://matthew.kerwin.net.au/