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 the 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?
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 preferringstr.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 anullwith a separatenullcheck, but the reverse order should be well understood and sufficiently differentiate the code from the normal case wherenullis forbidden.Working in security, some of the bugs null-tolerance accommodates are vulnerabilities.