73

Is Yoda worth it?

Today, I want to discuss the use of Yoda conditions.

Yoda condition

It’s a programming style, WordPress recommends its use but we’ll see you have to use it sparingly. Anyway, the following code is a Yoda condition :

if ( true == $the_force ) {
    $victorious = you_will( $be );
}

This is meant to prevent bad assignments :

 if ( $the_force = true ) {
    $victorious = you_will( $be );
}

This does not trigger any PHP error but the code fails. You are always victorious whether the Force is with you or not. We don’t want that!

Instead, the following will throw a fatal error :

if ( true = $the_force ) {
    $victorious = you_will( $be );
}

and it’s impossible to miss it.

Don’t be zealous

Use strict comparisons, it’s cleaner and safer :

if ( true === $the_force ) {
    $victorious = you_will( $be );
}

This way, you check both value and type.

However, the following code makes no sense :

if ( 40000 < $Ki ) {
    $victorious = you_will( $be );
}

It’s harder to read for nothing, WordPress has an explicit warning about that bad practice in its coding standards. The following is much much better :

if ( $Ki > 40000 ) {
    $victorious = you_will( $be );
}

Source

Yoda is just another technique

Examples

The idea with Yoda is to prevent stupid mistakes which would make our program fail.

BUT it just prevents the assignment error. Nothing more.

For example, the following code does not need Yoda :

if ( Ki_assess() == 20000 ) {
    return'This is your destiny';
}

It’s impossible to assign values to functions in PHP so you can try if (Ki_assess() = 20000) , it never works.

This is pretty much the same in JavaScript :

if ( "undefined" == typeof theData ) {
    var theData = {
        'lol': 'huge'
    }
}

Pretty useless, instead use the following strict comparison :

if ( typeof theData === "undefined" ) {
    var theData = {
        'lol': 'huge'
    }
}

The cons

A LOT of senior developers reject the Yoda style. They are not crazy. Most of the time, they find this style harder to read and ugly.

Who’s right ?

The answer is « experience« !

Readability is a concern. Yoda is fun in the movie (Yoda condition comes from Star Wars) but this is not the same when you need to read code fast to fix issues.

So Yoda might be terrible depending on your tastes.

Wrap up

Right to left and left to right is pretty much the same for me. If it’s not for you, that’s not a big deal at the end of the day. The following condition :

if ( 'LOL' === $value )

is not so ugly but I understand why a lot of people do not like it. I hope you too now.

However, the problem is not Yoda IMHO, it might be PHP that allows for assignment inside conditions which does not make sense.