DEV Community

Cover image for Yoda Conditions (From the office)
anastasionico
anastasionico

Posted on

Yoda Conditions (From the office)

I am Nico, 

I am a senior engineer for a ticket broker based in London.

From the office! is a daily (almost) posting routine that I keep to journal about the tech things I have been doing in my day-to-day office life.

Condition statements

Most often than not, while writing code, you need to perform different actions for different conditions. 

The way programming languages do it is by providing conditional statements.

In PHP, we have the following conditional statements:

The if statement executes some code if one condition is true.

if (condition) {
     code to be executed if the condition is true;
}
Enter fullscreen mode Exit fullscreen mode

The if...else statement has two blocks of code and executes the first if the condition is true, and the other code if that condition is false.

The if...else if...else statement executes different blocks of code for more than two conditions.

if (condition) {
  code to be executed if this condition is true;
} else if (condition) {
  code to be executed if the first condition is false and this condition is true;
} else {
  code to be executed if all conditions are false;
}
Enter fullscreen mode Exit fullscreen mode

The switch statement selects one of many blocks of code to be executed and provides a default option too.

Nothing too fancy here, if you have been through the basics of web development you know this stuff already.

The problem

You, as a developer, want your code to be reliable and working 100% of the time.

THAT IS QUITE A GOAL!

One of the most frequent ways to make the previous sentence incorrect is by introducing bugs into your code.

Well, stop it and just do not write buggy code, right?

The problem is that we often do not know when a bug in inside our code.

bug

I am sure you have seen this meme already

Let's test you now

if ($wheelsNumber == 2) {
    echo 'it is a motorbike';
}
if ($wheelsNumber = 4) {
    echo 'it is a car';
}
Enter fullscreen mode Exit fullscreen mode

Can you tell me what the bug is in this code?

Introducing the Yoda condition...

The Yoda condition explained

The reason Yoda condition is a thing, is that the code above ALWAYS returns 'it is a car'.

Even when we are dealing with a motorbike.

Why?

The way PHP works is by working out what is inside the condition's brackets and then evaluating the if keyword.

In the second condition, we are not actually evaluating a condition but we assigned the value of 4 to the variable named $wheelsNumber.

After the assignment is done the condition always returns true.

Solution

if (2 == $wheelsNumber) {
    echo 'it is a motorbike';
}
if (4 = $wheelsNumber) {
    echo 'it is a car';
}
Enter fullscreen mode Exit fullscreen mode

The outcome of this code will be a syntax error.

Now 4 is considered by PHP as a constant, and, you know, constants do not change.

The good

Catching errors

As I wrote above, I believe that your job is to make your code reliable all the time, this means preventing bugs at any cost.

Using Yoda condition is a simple way to avoid a bug, it takes 1 second to be written and it might save you an entire night in front of your screen to understand where the issue is coming from.

The bad

Bad Readability

"I understand the old C programmer's trick of inverting equality statements.  

It prevents the inadvertent omission of a = from being silent.  

But I don't like it. It doesn't read right. I prefer:

if (commentData == null)

CommentData is the subject of that sentence, and null is the direct object. Inverting them doesn't jive well with the way we think. I dislike any statement in code that causes the reader to do a double-take. Code that protects the author at the expense of the reader is flawed code."

The above paragraph comes from Uncle Bob, famous programmer and author of "The Clean Code series".

He has a point, writing a condition differently might take a couple of seconds for the reader to understand what were you doing.

Are those couple of seconds worth the danger of having a bug inside the code?

Don't even try to tell me that.

Not a universal standard

That might be a bigger issue to me:

Here are the platforms that actively encourage the use of Yoda:

Here who don't:

Don't get fooled by the two parts length, though.

Estimates say that in 2022 WordPress is still used by 43.2% of all

websites on the internet.

Do Unit tests instead

A better way to prevent bugs from getting and staying into your code would be by writing automated tests.

Let me rephrase it for you:

YOU MUST WRITE AUTOMATED TESTS!

There are amazing components nowadays that allow you to test in complete confidence.

See PHPUnit, Mockery, CodeCeption, Behat etc.

There is no excuse of not doing it, it is just too important

What is your take?

What do you think about the Yoda condition?

Is it worth adding it into your daily practice or it is just a waste of time for the readers of your code?

Write your thought in the comment below.

Conclusion

I have been a web developer for almost a decade now.

Working with world-class businesses and award-winning marketing agencies situated in the heart of London.

Also, I write articles and tutorials on my blog and online communities and help businesses build their presence online.

Click here to read more than 100+ of my blog post

Top comments (24)

Collapse
 
moopet profile image
Ben Sinclair

I can't stand yoda conditions.
They're much less readable and you're exploiting a side-effect of syntax to do something rather than relying on logic.

What I mean by this is that there are a lot of syntax errors you can make, and your IDE ot editor or linter will pick most of them up and at least warn you that you might be doing something incorrectly. It's just making work for yourself to try to take one part of that responsibility on.

It's like saying: "I need to take my wrecked car to get repaired except don't worry, I'll fix the left wing mirror myself".

Collapse
 
anastasionico profile image
anastasionico

Yes, I agree with you as it is not an ideal solution or a long-term one.
I don't like it either to be honest but at the same time I do not believe that everyone who is reading this article writes unit test all the time.

What solution would you give to the other readers to solve this? relying on the IDE?

Collapse
 
moopet profile image
Ben Sinclair

Relying on one automated system to monitor potential syntax errors, yes. That doesn't have to be the IDE, it could be a VCS commit hook running a linter or a code review tool or something.

Thread Thread
 
anastasionico profile image
anastasionico

yes I use PHPStan and GrumPHP with git prehooks (gosh I hate that guy what it appears in red in my terminal hahahah).

What other package do you use?

Collapse
 
tinussmit profile image
Tinus Smit

To me this seems like a whole lot of debate for something that's really not that big of a deal.

To me it looks like people

  • Write code directly in production without testing it themselves (a bigger problem than yoda or no-yoda).
  • Write code without testing / verifying the logic before handing it over to the users (the "if it compiles it works" mindset).

Both of these would make this issue seem much bigger than it really is. Additionally, this only works if one of the things being compared to is a constant (like a number). It likely yields no benefit if both items are variables.

If your language does not insist that the if statement has to be a Boolean expression (the statement has to yield true or false, otherwise you get a compiler / syntax error), then you simply have to be a little more vigilant.
I have to alternate between C# and JavaScript at times, and I've made the mistake in JavaScript once or twice. But I also pick it up almost immediately when I do a simple test of the code by running it. Understanding the language being used a bit more intimately would result in some sort of "preventative" mindset whereby you'd know if you're writing an if statement that your syntax requires == instead of = (in the cases of languages like C#, JavaScript, and many more).

A better alternative might even be to create methods with descriptive names that return a true or false where you have the freedom to create a more readable and testable bit of code.

Collapse
 
thomasjunkos profile image
Thomas Junkツ

To me this seems like a whole lot of debate for something that's really not that big of a deal.

Couldn't agree more.

Collapse
 
anastasionico profile image
anastasionico • Edited

hahaha yes.

what about readability vs reliability? that is a more interesting debate

Collapse
 
anastasionico profile image
anastasionico

Thanks for the comment and I definitely agree with you.

More than Yoda vs no Yoda, I point that I tried to make in the article is readability vs reliability.

I went against what uncle Bob said in his book because I think we should give priority to reliability.

What do you think?

Collapse
 
tinussmit profile image
Tinus Smit

I actually don't think those are mutually exclusive.

In my opinion...

Readability is about descriptive names (methods, classes, variables etc.), following conventions in naming; anything that helps a human understand the code. Can I hand this to another developer that doesn't have all my context and will they be able to understand the code soon? That's the question readability answers.

Reliability is about stuff like defensive coding, error handling, null checking; stuff that ensures that the code works as intended with the fewest possible crashes. Has the code been tested with a variety of scenarios and are the results what we intended each time / handled if not? That's what reliability answers.

There's room for both to exist at the same time.

You'll notice that I mention testing a lot, and that's a very key part of making sure that code is reliable. Untested code works in theory, but testing measures the reliability 😃

Collapse
 
phlash profile image
Phil Ashby

I used to promote the use of yoda conditions many years ago when reviewing C or Java code, indeed the recommendation existed in the corporate secure programming guide that I maintained for years, however I have now changed my mind, as there are better options and this syntactic trick was fragile: if you forgot to use it, the compiler / runtime didn't notice. Here's what I've recommend more recently:

  • Use a decent linter / static analyser / up-to-date compiler, they all pick this up now.
  • If your language supports it, and you are selecting from a set of constants, use a match clause (preferred) or switch statement (always with a default branch)
  • Use inequalities in conditional statements when it makes sense (it usually does once selection from a set of constants is handled as above). Inequalities are also more robust to discontinuities in the value being checked, especially so for non-exact types such as float!
Collapse
 
anastasionico profile image
anastasionico

That is such a great comment...
I belive the match statement is a great feature of PHP 8 expecially the fact that it can throw a UnhandledMatchError if no evaluation is equal found

so, do you replace the use of ifs with the one of matches in your code? can you show an example of it

Collapse
 
phlash profile image
Phil Ashby

I have a short example in Rust from my advent of code 2021 archive:
github.com/phlash/aoc2021/blob/tru...

this show a simple parser that selects an action based on a command word

Collapse
 
cicirello profile image
Vincent A. Cicirello

I'm curious why you say you previously would promote it when reviewing Java code? It doesn't seem like the issue should come up much in Java. Probably not at all. The condition if (x = 4) in Java will be a syntax error. The only way it might come up in Java is with a comparison of booleans such as if (y = true) but a Yoda condition isn't the right stylistic fix for that regardless of your view on Yoda conditions. It would better simply be if (y). Do you have an example of when this might be applicable to Java?

Collapse
 
phlash profile image
Phil Ashby

Literally because it was so long ago, and I've not touched Java in years, I said the wrong thing! I was probably meaning to say C++, we are talking mid 90s here 😄

Thread Thread
 
cicirello profile image
Vincent A. Cicirello

That makes sense. By the way, cool username both here and on GitHub.

Collapse
 
727021 profile image
Andrew Schimelpfening

Personally, I don’t think the trade-off of worse readability is worth it with yoda conditions. This is the kind of syntax error a good linter will catch; better to use tools designed to help with these kinds of syntax errors than to make your code more difficult to read and debug.

Collapse
 
anastasionico profile image
anastasionico

Hey Andrew, thank you for your comment.

I agree with you that a good linter and the use of PHPUnit should be a must and they are definitely better practices than Yoda conditions.

If I think at a cons, though, is that when I was just starting to code I didn't know how to Unit test not to mention how to use Composer.

Simply inserting Yoda condition can be a good start with for juniors.

What is your view on that?

Collapse
 
lexlohr profile image
Alex Lohr

For the love of code, please use a linter to avoid assignments in conditions instead of reducing your code's readability. This crucial tool nowadays is even available for PHP, as well as for other languages.

Collapse
 
anastasionico profile image
anastasionico

Cannot agree more

Collapse
 
jessekphillips profile image
Jesse Phillips

I don't agree with the readability complaints. I find it hard to write.

The real issue is your language allows you to do this. And why others talk of lint tools.

Collapse
 
anastasionico profile image
anastasionico

shouldn't PHP allow to write them?

Collapse
 
jessekphillips profile image
Jesse Phillips

Yoda? Sure, but not an assignment in the if condition.

Collapse
 
anastasionico profile image
anastasionico

Have you ever used Yoda condition in your code? what happened next?

Collapse
 
suckup_de profile image
Lars Moelleken

Modern tooling for the rescue: e.g. in PHP you can prevent assignments in conditions via github.com/spryker/code-sniffer/bl...