Saturday, November 28, 2015

Programming Jargon: Yoda Condition


I have been in the software development industry for almost 10 years but it was only recently that I learned about the programming jargon Yoda Condition

It all started when my code reviewer noticed an if-condition similar to the following:

if (stringVariable.equals(STRING_CONSTANT)) {

}
He pointed out that it’s not null pointer-safe so I said I’ll just change the condition into this:

if (stringVariable != null && stringVariable.equals(STRING_CONSTANT)) {

}
That was the time that he mentioned about a better way to rewrite the above if-statement using the Yoda Condition and I had a big question mark on my face upon hearing it. After asking Mr. Google, I found out that in Yoda Condition you have to place the constant on the left side of the comparison operator while the variable is on the right side. Obviously, it was named after the Star Wars character Yoda who speaks English using the form object-subject-verb (e.g. Apple I eat).

Using the Yoda Condition, the previous if-condition sample will now be translated into this:

if (STRING_CONSTANT.equals(stringVariable)) {

}
The above code makes the condition null pointer-safe since the constant is not nullable.

Now, my opinions about the Yoda Condition:
  • Using the above example, I still prefer manually checking the stringVariable for null pointer errors early in the code to avoid having issues later on caused by a null string variable.
  • I find using Yoda Condition quite awkward and take some time to get used to it. Just take a look at the following example:

if (7 == intVariable) {

}
Awkward, isn’t it?

Are you already using Yoda Condition in your daily coding? Let me know in the comment section below.  
  
Source: https://en.wikipedia.org/wiki/Yoda_conditions 

No comments:

Post a Comment