Page MenuHomePhabricator

New Sniff for using pointless variables before return
Closed, DeclinedPublic

Description

We often see code like

$foo = 'bar';
return $foo;

The code should just do

return 'bar';

Same for any functions

$foo = MyFooClass::newFromBar( 'bar' );
return $foo;

should just be

return MyFooClass::newFromBar( 'bar' );

It's just pointless extra operations and assignments

Event Timeline

Just for the record:
This has to check, if the variable is never used before, because some cache results are set directly before a return[1]
It should not the function argument, which could be changed and returned back to the caller.

From the first look at this could be harder to resolve, I am not sure if a static code analizer like phan could do this easier, because he know what is a variable and what happens with the assignment, if there are if-else-parts to check, etc.

[1] https://gerrit.wikimedia.org/r/#/c/408583/1/includes/GlobalBlocking.class.php

Possible counter-example:

$foo = 'thing';
$foo = aaa( $foo, 1 );
$foo = bbb( 'x', $foo );
$foo = ccc( $foo, 'x', 'z' );
return $foo;

I don't think useless variables harm readability, not maintainability, nor performance. Nor do I think of them as their own code pattern or concept where having fewer would reduce cognitive overhead from having less ways to do the same thing. So I don't think we'd gain from removing this pattern in the places where an author choose to follow it.

Having said that, I also don't see any harm in readability etc from not having the useless variable, so if others prefer we enforce consistency on not having it, I'd be supportive of that. We seem to have uncontroversially removed so far, so there seems consensus or neutral thoughts in that regard currently.

I do think that if we go for this, there'd be a small amount of value in allowing chains to exist, e.g. detectable as assignments that include the variable in their expression.

With a debugger, a separate return is actually convenient as it allows you to inspect the result that's being returned.

What @Krinkle and @Tgr said. Personally, I do not use this style. I try to find other ways to make my code readable and self-explanatory. But I know certain developers (e.g. @daniel) use this style all the time. I don't think our code becomes more readable when we block these people from continuing to do so. The contrary: an auto-fix would remove a named variable, and potentially make code less readable because of this. So: 👎

DannyS712 subscribed.

Per above, there are valid reasons to have a variable assigned right before a return, including that its a static variable, a variable passed by reference, or for readability or debugging -> not warranted as a codesniffer rule, but can be done manually as needed