DEV Community


Discussion on: Why using Yoda conditions you should probably not be

andrewmcguinness profile image
Andrew McGuinness

In some languages (like java) yoda-conditions also give you null handling:

if (variable.equals("value")) ...

throws an exception if variable is null

if ("value".equals(variable)) ...

will work correctly

if ((variable != null) && variable.equals("value")) ...

is more work and potentially error-prone.

dean profile image
Dean Bassett

Now there's Objects.equals(variable, "value") as well... although it looks sloppy at first it's very useful for lambdas

maxart2501 profile image
Massimo Artizzu • Edited

Can you really call it a "Yoda condition"?

Yoda conditions have been born to avoid hard-to-catch mistakes, like an assignment in a condition statement. If variable is null in your first example you catch it immediately, because it throws a NullPointerException as you mentioned.

So it doesn't save you from a mistake; it saves you from checking if the value is null or not. And honestly I'm not sure it's what I'd want: if I expect a string there, why am I dealing with null?

greg0ire profile image
Grégoire Paris Author

TIL. That's a good usage of Yoda conditions.