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.

Leave a Comment