Skip to main content

Command Palette

Search for a command to run...

Embrace the Force: Yoda conditions

Updated
1 min read
A

With more than 10 years in IT, I had a chance to work in different areas, such as development, testing and management. I had a chance to work with PHP, Java, Python and .Net platforms with different application from microservices to monolithic and monstrous desktop UI applications.

Currently, I am holding the position of Senior Software Engineer, but I prefer to consider myself a full-stack engineer.

My passions are quality and efficiency. Agile fan and XP practitioner.

Many things in programming are not super intuitive. Yet, such small things could be a life saviours.

One of such things is Yoda conditions style.

Baby Yoda Cartoon Wallpapers - Top Free Baby Yoda Cartoon Backgrounds ...

Consider the code bellow:

if (variable == 3) {
    // do something
}

This would be the way most of us write conditionals.

However, some language would also allow to write something like this:

if (variable = 3) {
    // ALWAYS do something :)
}

It just one symbol difference, but the effect could be VERY different.

All of a sudden, you don’t compare anything, in JavaScript, for example, you will blindly assign 3 to the variable and always execute the code.

So, here comes “the force”:

if (3 == variable) {
    // Yoda conditions
}

This is called “Yoda conditions” and it will make the previous mistake virtually impossible. It reads awkward (at first), but after some practice it could become your second nature.

Extra-tip

Similarly, in Java you could avoid string related Null Pointer Exceptions by writing Yoda string conditions:

if ("value".equals(variable)) {
    // do something
}

It is small, and it could look awkward at first, but boy, it is useful. If you have other similar useful tricks - please share!

E
Edhar10mo ago

❌ null-points ✅ NullPointerException (NPE) s

1
A

nice catch