tags:

views:

68

answers:

3

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, 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 ?

+2  A: 

It's an easy way for errors to sneak in, but it's common practise in PHP. Especially during things like directory traversals where you're doing things like while (($dir = readdir($handle)) !== FALSE)

If you can avoid it. Avoid it.

jlindenbaum
+1  A: 

While this is valid syntax and the results will be as expected, it is a bad habit. The readability is lacking, there is a potential to develop a bad habit of putting = when you meant ==, and your eyes will keep returning to this line when you are trying to find real bugs within an application. I would not use this writing style. In this case, just get the return value and then verify the return value... or better yet, use exception handling to avoid getting bogged down with lots of if statements.

Freebytes
+1 this is a leftover from C days, where this was common (bad) practice. A lot of people still do this because they think it makes them [look clever](http://stackoverflow.com/questions/2101875/what-are-some-programming-questions-or-mistakes-you-get-wrong-only-as-you-get-b/2151844#2151844).
BlueRaja - Danny Pflughoeft
+1  A: 

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.

Rob Wilkerson