Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In PHP, is too many assignments are considered bad? If so why?

Tags:

php

Netbeans seems to suggest too many assignments is quite bad and should be changed.

i.e.

$foo = ' bar ';
$foo = trim($foo);

Should better coded as

$foo = ' bar ';
$trimmed_foo = trim($foo);

Is this acceptable? If so why? I know I can switch this particular hint type off in setting, but just checking if someone spotted anything for this.

like image 683
xelber Avatar asked Mar 06 '13 02:03

xelber


2 Answers

Ths is a new warning, circa mid 2012.

Since you used the trim example I'm guessing that you have read this https://blogs.oracle.com/netbeansphp/entry/several_new_hints, which tries to explain the warning. My take on this warning is that it's trying to warn you about accidental reuse of a variable. As such it is very handy. In the trim case you give it seems a bit heavy handed. If the reassignment is on he following line, it's probably not accidental.

like image 112
Peter Wooster Avatar answered Oct 16 '22 14:10

Peter Wooster


Ideally the variable name should describe the contents. If you are repeatedly assigning to the same variable, it suggests that the variables contents are not well defined.

Additionally, if your code has something like this:

$foo = ' bar ';
// some code, mybe 100 lines of it
// now do something with $foo

What happens if you update the code to add $foo = trim($foo); up above? You break the code below.

like image 24
Niet the Dark Absol Avatar answered Oct 16 '22 13:10

Niet the Dark Absol