Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assignment in conditionals

Tags:

php

I've seen a lot this kind of code recently:

if ($foo = $bar->getFoo())
{
    baz($foo);
}

Is this considered good or bad practice?

For example, the NetBeans IDE give a notice if you use this kind of code:

Possible accidental assignment, assignments in conditions should be avoided

What do you think?

like image 971
DuoSRX Avatar asked May 14 '10 14:05

DuoSRX


1 Answers

It's a useful tool that I have to admit to using on occasion to avoid an extra line for an assignment. On the one hand, it may be bad practice by some because:

  • It's not an available idiom in other common languages
  • It's less readable

On the other hand:

  • Implicit boolean conversion doesn't occur in other languages, but they're widely counted on where they do exist. Conversely, conditional assignment operators exist in Ruby and Javascript (as examples), but not in PHP. Should we limit our use of language constructs only to those found in all similar languages? Probably not.
  • Less readable to whom?

I should note that I do try to avoid it because I find it less readable most of the time, but it's purely personal preference for me. Where I find it useful, I use it.

like image 129
Rob Wilkerson Avatar answered Sep 28 '22 06:09

Rob Wilkerson