Sundarrajk's Weblog

PMD – String and StringBuffer Rules

Posted on: September 28, 2011


This is the seventeenth installment giving details of PMD rules covering String and StringBuffer rules.

String and StringBuffer Rules

These rules deal with different problems that can occur with manipulation of the class String or StringBuffer.

AvoidDuplicateLiterals

Code containing duplicate String literals can usually be improved by declaring the String as a constant field.

Example

public class Foo {
private void bar() {
    buz("Howdy");
    buz("Howdy");
    buz("Howdy");
    buz("Howdy");
}
private void buz(String x) {}
}

StringInstantiation

Avoid instantiating String objects; this is usually unnecessary.

Example

public class Foo {
private String bar = new String("bar"); // just do a String bar = "bar";
}

StringToString

Avoid calling toString() on String objects; this is unnecessary.

Example

public class Foo {
private String baz() {
  String bar = "howdy";
  return bar.toString();
}
}

InefficientStringBuffering

Avoid concatenating non literals in a StringBuffer constructor or append().

Example

public class Foo {
void bar() {
  // Avoid this
  StringBuffer sb=new StringBuffer("tmp = "+System.getProperty("java.io.tmpdir"));
  // use instead something like this
  StringBuffer sb = new StringBuffer("tmp = ");
  sb.append(System.getProperty("java.io.tmpdir"));
}
}

UnnecessaryCaseChange

Using equalsIgnoreCase() is faster than using toUpperCase/toLowerCase().equals()

Example

public class Foo {
  public boolean bar(String buz) {
    // should be buz.equalsIgnoreCase("baz")
    return buz.toUpperCase().equals("baz");
    // another unnecessary toUpperCase()
    // return buz.toUpperCase().equalsIgnoreCase("baz");
  }
}

UseStringBufferLength

Use StringBuffer.length() to determine StringBuffer length rather than using StringBuffer.toString().equals(“”) or StringBuffer.toString().length() ==.

Example

public class Foo {
void bar() {
  StringBuffer sb = new StringBuffer();
  // this is bad
  if(sb.toString().equals("")) {}
  // this is good
  if(sb.length() == 0) {}
}
}

AppendCharacterWithChar

Avoid concatenating characters as strings in StringBuffer.append.

Example

public class Foo {
void bar() {
  StringBuffer sb=new StringBuffer();
  // Avoid this
  sb.append("a");
 
  // use instead something like this
  StringBuffer sb=new StringBuffer();
  sb.append('a');
}
}

ConsecutiveLiteralAppends

Consecutively calling StringBuffer.append with String literals

Example

public class Foo {
private void bar() {
   StringBuffer buf = new StringBuffer();
   buf.append("Hello").append(" ").append("World"); //bad
   buf.append("Hello World");//good
}
}

UseIndexOfChar

Use String.indexOf(char) when checking for the index of a single character; it executes faster.

Example

public class Foo {
void bar() {
  String s = "hello world";
  // avoid this
  if (s.indexOf("d") {}
  // instead do this
  if (s.indexOf('d') {}
}
}

InefficientEmptyStringCheck

String.trim().length() is an inefficient way to check if a String is really empty, as it creates a new String object just to check its size. Consider creating a static function that loops through a string, checking Character.isWhitespace() on each character and returning false if a non-whitespace character is found.

Example

public class Foo {
    void bar(String string) {
        if (string != null && string.trim().size() > 0) {
                   doSomething();
       }
    }
}

InsufficientStringBufferDeclaration

Failing to pre-size a StringBuffer properly could cause it to re-size many times during runtime. This rule checks the characters that are actually passed into StringBuffer.append(), but represents a best guess “worst case” scenario. An empty StringBuffer constructor initializes the object to 16 characters. This default is assumed if the length of the constructor can not be determined.

Example

public class Foo {
    void bar() {
        StringBuffer bad = new StringBuffer();
        bad.append("This is a long string, will exceed the default 16 characters");//bad
        StringBuffer good = new StringBuffer(41);
        good.append("This is a long string, which is pre-sized");//good
    }
}

UselessStringValueOf

No need to call String.valueOf to append to a string; just use the valueOf() argument directly.

Example

public String convert(int i) {
  String s;
  s = "a" + String.valueOf(i); // Bad
  s = "a" + i; // Better
  return s;
}

StringBufferInstantiationWithChar

StringBuffer sb = new StringBuffer(‘c’); The char will be converted into int to intialize StringBuffer size.

Example

class Foo {
  StringBuffer sb1 = new StringBuffer('c'); //Bad. This is wrong, not bad.
  StringBuffer sb2 = new StringBuffer("c"); //Better
}

UseEqualsToCompareStrings

Using ‘==’ or ‘!=’ to compare strings only works if intern version is used on both sides

Example

class Foo {
  boolean test(String s) {
    if (s == "one") return true; //Bad
    if ("two".equals(s)) return true; //Better
    return false;
  }
}

AvoidStringBufferField

StringBuffers can grow quite a lot, and so may become a source of memory leak (if the owning class has a long life time).

Example

class Foo {
        private StringBuffer memoryLeak;
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

%d bloggers like this: