These rules deal with different problems that can occur with manipulation of the class String or StringBuffer.
Code containing duplicate String literals can usually be improved by declaring the String as a constant field.
This rule is defined by the following Java class: net.sourceforge.pmd.rules.AvoidDuplicateLiteralsRule
Here's an example of code that would trigger this rule:
public class Foo { private void bar() { buz("Howdy"); buz("Howdy"); buz("Howdy"); buz("Howdy"); } private void buz(String x) {} }
This rule has the following properties:
Name | Default value | Description |
---|---|---|
threshold | 4 | The number of duplicate literals reporting threshold |
Avoid instantiating String objects; this is usually unnecessary.
This rule is defined by the following Java class: net.sourceforge.pmd.rules.StringInstantiation
Here's an example of code that would trigger this rule:
public class Foo { private String bar = new String("bar"); // just do a String bar = "bar"; }
Avoid calling toString() on String objects; this is unnecessary
This rule is defined by the following Java class: net.sourceforge.pmd.rules.StringToStringRule
Here's an example of code that would trigger this rule:
public class Foo { private String baz() { String bar = "howdy"; return bar.toString(); } }
Avoid concatenating non literals in a StringBuffer constructor or append().
This rule is defined by the following Java class: net.sourceforge.pmd.rules.AvoidConcatenatingNonLiteralsInStringBuffer
Here's an example of code that would trigger this rule:
public class Foo { void bar() { // Avoid this StringBuffer sb=new StringBuffer("AAAAAAAAAA"+System.getProperty("java.io.tmpdir")); // use instead something like this StringBuffer sb = new StringBuffer("AAAAAAAAAA"); sb.append(System.getProperty("java.io.tmpdir")); } }
Use String.equalsIgnoreCase rather than String.toUpperCase().equals()
This rule is defined by the following Java class: net.sourceforge.pmd.rules.UnnecessaryCaseChange
Here's an example of code that would trigger this rule:
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"); } }