最好把字符串数据放在equals()或equalsIgnoreCase()的左侧。
这样可以避免空指针异常,因为字符串数据永远不可能为null。
如下代码:
String myString = null;
System.out.println("Equal? " + myString.equals("foo")); // Non-Compliant - will raise a NPE
System.out.println("Equal? " + (myString != null && myString.equals("foo"))); // Non-Compliant - null check could be removed
应该重构为:
System.out.println("Equal?" + "foo".equals(myString)); // Compliant - properly deals with the null case