Have you ever heard about Yoda conditions?

Skrew Everything
From The Scratch
Published in
3 min readApr 17, 2018

I used to code in C and Java a lot during my initial programming days. The most common mistake I would do is using = instead of == inside conditional statements.

Everybody says that finding a missing semi colon is very stressful. Like this memes….

The truth is they are wrong!

Compilation Errors are the easiest errors to solve while programming.

Because the compilers can point to the exact line where the error has occurred.

So, next time when ever you see people saying about that, just think they are try-hards and noobs!

The most difficult to solve errors while programming are logic errors.

The worst thing about this type of errors is: The program runs silently🤫.

These are usually called as Bugs🕷.

One of the annoying logic errors I have ever faced while programming is using = instead of == inside conditional statements.

For example, I want to check for a particular number in if condition.

I want to write like this:

void checkNumber(int a)
{
if(a == 13)
{
printf("Number is 13");
}
}

Instead, I wrote = in the if condition:

void checkNumber(int a)
{
if(a = 13) // This is where a Bug is born!
{
printf("Number is 13");
}
}

So, every time I run this method, I always get Number is 13 irrespective of the given number a.

To avoid this type of Bugs, we can reverse the order in the if conditions.

Instead of this,

if(a = 13)
{
//This assigns 13 to a instead of evaluating the desired condition
}

We write it like this,

if(13 = a)
{
// This is a syntax error and will not compile
}

Since 13 is a constant and can not be changed, this error will be caught by the compiler.

Same can be followed in Java also. The most frequent logic error we perform is, instead of checking for null we assign null to a variable.

if(someVar == null) // Instead of this
{
}if(someVar = null) // We might do this
{
}

Yoda Conditions:

Reversing the order in conditional statements is known as Yoda Conditions.

Why name it as Yoda?

In programming jargon, Yoda conditions (also called Yoda notation) is a programming style where the two parts of an expression are reversed from the typical order in a conditional statement. A Yoda condition places the constant portion of the expression on the left side of the conditional statement. The name for this programming style is derived from the Star Wars character named Yoda, who spoke English in a non-standard syntax.

The disadvantage is:

Lack of readability. But is it really worth when you are thinking why your program is not running as expected at 3A.M?

--

--

Skrew Everything
From The Scratch

A wannabe artist 👨‍🎨, but can’t draw 😫. A wannabe athlete 🏃‍♂️,but can’t run 🥵.Found my peace with coding 👨‍💻 and writing ✍️. Twitter.com/SkrewEverything