h1

Coding Standard: String Literals and equals()

January 25, 2007

Coding Standard:

Use “some String literal”.equals(myString) instead of myString.equals(”some String literal”).

Justification:

It saves a null check.

Example of Violation:

String myString = getSomeString();
if ((myString != null)
  && (myString.equals("some String literal"))) {
    // do something important
}

Example of Correction:

String myString = getSomeString();
if ("some String literal".equals(myString)) {
  // do something important
}

Explanation:

When calling the equals method on a String object, there’s always a chance that the object is null. If you don’t check for it, you’re just asking for a NullPointerException. So there are two ways to handle this. Either check for null and then call the equals method if the String is not null, or turn around the logic and call the equals method on your String literal (which you know is not null). Both work fine. The latter saves you a null check and simplifies the conditional logic.

This standard can be enforced in JTest by enabling the PB.ISEM rule.

I haven’t found a rule in Checkstyle to enforce this. If anyone knows of such a rule, or a similar rule in another coding standards tool, feel free to post it in the comments.

See Also:


Automate Your Coding Standards Checks


Resources:

JTest is made by Parasoft.

http://www.parasoft.com/

Checkstyle is written by Oliver Burn and is an open source project at SourceForge.net.

http://checkstyle.sourceforge.net/

Effective Java Programming Language Guide is a book that deals with coding standards and best practices in Java. It is available at Amazon.com.

Technorati Tags:

Leave a Comment