📜 ⬆️ ⬇️

Assignments in conditions

Recently, during a code review on my project, I had a disagreement with my colleagues. They concerned the following code:

if (false == ($var = foo())){...}

At once some really good developers considered this code absolutely unacceptable. Particularly revealing was the argument of my colleague Timothy: “Assignments in conditions are evil, they are told about this in the first lecture on programming”. It is possible, but because I have not had a single lecture on programming, I suggest, nevertheless, to understand why this is evil.

So, all of you know how conditions and comparison operators work in php.
In the example below, the value of the $ var variable is reduced to a boolean, and if it is true, the condition is satisfied.
if ($var){...}

This example compares the values ​​of the $ var variable and the result of foo (), and if they are equivalent, the condition is satisfied.
if ($var == foo()){...}

Here, in the condition of the $ var variable, the result of foo () is assigned, after which the value of $ var is reduced to Boolean, and if it is true, the condition is satisfied.
if ($var = foo()){...}

Although the last example is valid in php, it is really hard to read, because there are no comparison operators in the condition. Often this code is an error, and the programmer actually meant
if ($var == foo()){...}

When comparing a variable with a boolean value based on the type, it is often written like this
if (true === $var){...}

This is done precisely in order to avoid the random assignment of $ var to the value of true, for example
if ($var = true){...}

The IDE also tries to warn the developer if he uses the assignment in the condition. Here is an example from Eclipse

')
Let's go back to the code that caused the controversy.
if (false == ($var = foo())){...}

Here the variable $ var is assigned the result of executing foo (), which is compared with false. The difference between this example and the one I wrote in Eclipse is that here the main element of the condition is clearly present - the comparison . This code is perfectly readable and leaves no space for possible typos. Eclipse considers it valid


It is convenient to use such code when the variable defined in the condition will be used only inside the if construction. In all other cases, it is better to remove the initialization of the variable from the condition.

Source: https://habr.com/ru/post/141746/


All Articles