Condition Yoda, good reason to use?

Asked

Viewed 289 times

15

Question mainly in PHP, in the Wordpress documentation exists an excerpt which explicitly speaks that it is interesting to use the famous Yoda conditions, although it does not give a good and real reason.

When making logical comparisons involving variables, always put the variable on the right side and put constants, literals or calls function on left side. (Free Translation)

Specifically me, always found ugly and read not easy this kind of coding: if(10 == $teste){ // do anything } or if("string" == $teste){ // do anything }

This doubt arose me after a colleague of mine recommend me to install a plugin in Brackets called Brackets php code quality tools that theoretically points out errors in coding... and in lines of the type if($teste == 10){ // do anything } he generates warnings, he recommends the use of the blessed Yoda conditions.

The first time I saw this type of coding came into my mind to be to facilitate the processing, like first the processor just picks up the constant and then accesses the location of the variable in memory, but stopping to think I see no difference!

I did tests in PHP and Javascript and saw no difference in performance with the naked eye...

Follows tests:

PHP

echo "Normal<br/>";
$a = "a";
for($x = 0; $x <= 5; $x++){
    $time_start = microtime(true);
    if($a == "a"){
        //
    }
    $execution_time = microtime(true) - $time_start;
    echo $execution_time.'s<br/>';
}
echo "-------------<br/>";
echo "Yoda Condition<br/>";
$a = "a";
for($x = 0; $x <= 5; $x++){
    $time_start = microtime(true); 
    if("a" == $a){
        //
    }
    $execution_time = microtime(true) - $time_start;
    echo $execution_time.'s<br/>';
}

inserir a descrição da imagem aqui

Javascript

inserir a descrição da imagem aqui

Is there a good reason to use Yoda Conditions in some programming language? Or is it just the customer’s taste? Is there any difference in performance (in some language)?

inserir a descrição da imagem aqui

  • 4

    Using Yoda condition the elaborate question was. Good padawan you are.

3 answers

16


The only advantage of Yoda conditions is change the error type, logic (assignment instead of comparison) by a syntax. It is not possible to assign something directly to a number or any other type.

Basically Yoda conditions make the code fail faster in case of errors while performace is still the same comparison; so it does not affect anything.

Is it worth sacrificing readability to detect this kind of mistake sooner? It is a simple mistake that can sometimes cause a little headache, in these situations it is best to take a break and cool your head.

<?php
$usuario = 'teste';
if('admin' = $nome){
    echo 'administrador do sistema';
}

PHP Parse error: syntax error, Unexpected '='

Example - ideone

  • I’ve been researching and found a website that says that many programmers (including me) think that benefits are not so big as.... if the condition has an assignment instead of a comparison, either way you will get an error rs

  • @Marcelobonifazio also doesn’t think Yoda conditions is cool. Which of the two is easier to find a logic or syntax error? : P It is the only advantage (advance the error) see that this sacrifices the readability. Is it really worth it? I think not.

  • Then see..... you go there, write the correct code if(a == "a"){ and the blessed plugin that even gives some cool tips and help enough goes there and drops a Warning..... I don’t even know what to say!

  • @Marcelobonifazio Swap the plugin :P I imagine you have an option to ignore this specific rule.

  • 1

    Great answer. I would just suggest improving the sentence (which was not clear unless your intention was also to play Yoda rs) "Basically Yoda conditions make the code fail faster as the performace is still the same comparison so it does not affect anything." for something like "Basically Yoda conditions make the code fail faster in case of typos, as the performace comparison is maintained the same; therefore does not affect at all in the execution."

  • 1

    @Luizvieira Thank you for the suggestion, edit the reply :)

  • 3

    Interestingly, a company recently lost about R$1 million for making a mistake in reverse. Instead of assigning a value to a variable, the code snippet compared whether the two values were equal. For those interested, the link.

Show 2 more comments

9

Java uses something similar for comparisons involving a literal string (between quotes) or another already instantiated object:

if ("Mario".equals(nome)) {

The utility is to save a null reference test. If the programmer doesn’t want to do this check or forget to do it, but is used to reversing the condition, you can avoid a NullPointerException that could occur if called equals() from a null reference.

4

The advantage of Yoda conditions is to expose possible bugs by typos, replacing a == for =.

In the code below, the condition will always return true, causing unexpected application behavior - which could take some time to discover.

<?php
$usuario = 'teste';
if($usuario = 'admin'){
    echo 'administrador do sistema';
}
?>

Using Yoda condition, you would receive a syntax error while running this code, noticing and fixing the problem immediately.

<?php
$usuario = 'teste';
if('admin' = $usuario){
    echo 'administrador do sistema';
}
?>

So you get a performance gain not in code execution, but in preventing bugs.

Browser other questions tagged

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