Should I declare a variable within the "if" or separate condition?

Asked

Viewed 1,147 times

10

I need to call a function that can return false or a value, and in case it returns the precise value manipulate it.

So I made a code similar to the one below:

//A função que é chamada é muito mais complexa do que essa, estou utilizando apenas como exemplo para a demonstração.
public function divisao($a,$b){
    if($b > 0){
        return $a / $b;
    }else{
        return false;
    }
}


//Em outro trecho do código
....
if($resultado = divisao($variavel1,$variavel2)){
   //Faça alguma coisa com o resultado
}else{
   //Faça outra coisa
}
...

My question giving focus to the latter if would be: is a good practice to put the return of the function already assigning it to the variable and testing everything in the same line (within the if)? If not, why not be good practice?

I know the code could be written as follows:

$resultado = divisao($variavel1,$variavel2);
if($resultado){
   //Faça alguma coisa com o resultado
}else{
   //Faça outra coisa
}

2 answers

11


There are controversies as to the subject of the question.

Some people find it less readable. Some have established a rule that everything that generates side effect (change of state) should be on a separate line in a clearer way, after all wrong state change is usually the biggest reason for generating bugs and where else you have to debug (note that a debug all the time you’re looking at the changing state of the variables to see what happened).

On the other hand it can be a bit of an exaggeration to follow the rule blindly. Is it so hard to visualize that you have an assignment there?

But we can also lean the other way again. Did you want to compare the variable with the return of the function, IE, I wanted to use == which is the comparison and not the allocation operator?

What do you actually get by putting in the same line? If you don’t have a very clear gain don’t use. From the look of your code, it looks like you’re trying to get some typing, which is a silly thing, so that’s not a good reason.

I’m actually more concerned with returning values of different types in the function. A dynamic language allows this, but should it? Does it work well? see a situation that doesn’t work:

<?php
function subtracao($a, $b){
    if ($b > 0) return $a - $b;
    else return false;
}
if ($resultado = subtracao(4, 4)) echo "entrou";
else echo "não entrou";
if ($resultado = subtracao(4, 0)) echo "entrou";
else echo "não entrou";

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

So forget this good practice business, understand the motivations to use one thing or another. See if you have a real problem.

  • Your explanation is excellent.

  • On the question of the type of return, the situation is not similar to the use of types nullable in typed languages? The use of these types can be a problem in them?

  • 4

    Not exactly, it’s a problem, but apparent, because it breaks the application (in modern languages, like C# 8, already indicates in compilation that will give problem), in PHP it only runs something in an unexpected and wrong way. But the problem is not that language is dynamic, it’s that it’s weak. If it had strong typing, even if it was dynamic, it would give an error because receiving a 0 where one expects a boolean to break the typing. Returning types differts is no problem, treating two types as if it were the same thing is problem.

3

On the use of good practice

Something "Ideal" is relative when it comes to programming practices, but instead of discussing it I will try to answer objectively. I find the question of Pernambuco due to the fact that you are seeking to have a different vision about the code and try to learn from it. It is important to remember that this is often a matter of taste and therefore not a unanimity among programmers. Knowing this, follows the answer for each case cited.


First case

To simplify the code, you could use the technique Early Return which consists of returning before to avoid the use of a else. For example:

if($b > 0){
    return $a / $b;
}

return false;

You could also reverse the logic and continue applying Early Return:

if($b === 0){
   return false;
}

return $a / $b;

Remembering once again that this is more a matter of taste than of "right" or "wrong". Stop using else is an option, but do not follow any practice rigidly if it is not advantageous.


Second case

You can assign and test the variable at the same time within the expression tested in if, however this does not seem very readable. So assign a value to the variable $resultado first and then testing seems a better option.

Leaving everything on the same line leaves the code confused at times, PHP allows this and when this practice is done in exaggeration it seems that the code went through a minification of Javascript, which is bad for readability.

  • Many of my codes I make use of Early Return. As a matter of taste, I think it gets a little clearer the code. But as said by @Maniero’s great explanation I see no problem using more than one if if necessary. I make use of else if inclusive. =)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.