String.equals() argument ordering

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.


Visit the following link to understand what is meant by Yoda Conditions|Notation

Its not a "poor coding style" its diferent way of coding.

Yoda can be usefull to track typos in some languages, i believe the -1 was not deserved to be honest but that is my personal opinion.

But Yoda can be bad as explained in this lengthy but very interesting article.

End of the day, there are supporters in favor and against this kinda of notation.