A Case For Yoda.

Jedi Burrell
2 min readJul 22, 2017

--

A week or so ago, I was reading about “Yoda Conditions” in programming. The idea is that in your conditions, you start with the literal to the left side of the statement.

By using yoda conditions, you know that the left-hand operator is not null. When your left-hand operator is null, and you try to instigate an equals (or other) check, a NullPointerException will be thrown. Using yoda conditions guarantees that true is not equal to null.

One solution is to check if it’s null first. Sure, that’ll make sure that a NullPointerException won’t be thrown, but it’s unconventional, and requires additional nesting.

Image by oppressive-silence.com

Besides preventing a NullPointerException, some people argue that by using yoda conditions you won’t accidentally set something inside of the if statement. This has never been an issue with me, so I can’t say this is a “no-brainer”, but I can say it is a fail-safe.

Yoda conditions are criticized for “lack of readability”, and sure, “true equals to isCrazyMurderingRobot” isn’t exactly the most readable thing; but there is a workaround! You can make a comparison function.

Kotlin

fun compare(p0 : Any, p1 : Any) : Boolean {
if (p0==null) return p1==p0
else return p0==p1
}

Java

public static boolean compare(Object p0, Object p1) {
if (p0==null) return p1==p0
else return p0==p1
}

You can also do a single lined compare function in Kotlin if you absolutely will not use yoda conditions.

fun compare(p0 : Any, p1 : Any) : Boolean = p1==p0

Now, you can just use compare.

if(compare(a, b))

Oh, and don’t use ==true; that’s obsolete.

--

--