I recently received a downvote for using the following in a recent answer:
String word = ...; if ("s".equals(word) || "y".equals(word)
The downvote was given due to using a "yoda condition". I asked for further explanation but none was provided. I prefer this style to avoid a possible NullPointerException
.
Is this a poor coding style? If so, why?
You should not use == (equality operator) to compare these strings because they compare the reference of the string, i.e. whether they are the same object or not. On the other hand, equals() method compares whether the value of the strings is equal, and not the object itself.
StringUtils class also has equalsIgnoreCase() and compareIgnoreCase() method, which are similar to the equals() and compare() method except they ignore the case of both strings. That's all about comparing two strings in Java.
equals() method in Java. Both equals() method and the == operator are used to compare two objects in Java. == is an operator and equals() is method. But == operator compares reference or memory location of objects in a heap, whether they point to the same location or not.
== confirms if there is reference-equality Equals confirms if the objects contains are same. Example of reference-equality is IdentityHashMap. There could be a case in which Only the object inserting something to IdentityHashMap has the right to get/remove the object.
Bill Pugh asked this question at Devoxx 2011. The vast majority of people went for the form "xyz".equals(str)
. I am with Bill, now preferring str.equals("xyz")
.
It's fundamental to the Java tradition that we find errors as early as reasonably possible. NPEs are exceptionally common. We want to route these nulls out as soon as possible.
If you're expecting the reference to maybe null
, then I don't particularly object to the backwards notation. It's nice to be explicit and easier to understand that there may be a null
with a separate null
check, but the reverse order should be well understood and sufficiently differentiate the code from the normal case where null
is forbidden.
Working in security, some of the bugs null-tolerance accommodates are vulnerabilities.
Yoda conditions (i.e. putting a constant before a variable in a comparison) can be considered bad practice as it makes the line of code less comprehensible. In this specific case however I would state that using a Yoda condition makes the code more comprehensible as you don't have to put a extra null check in front of it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With