forked from phoedos/pmd
Fix #3374 - UseStringBufferForStringAppends: Wrong example in documentation
This commit is contained in:
@ -1138,13 +1138,22 @@ threadsafe StringBuffer is recommended to avoid this.
|
||||
<example>
|
||||
<![CDATA[
|
||||
public class Foo {
|
||||
void bar() {
|
||||
String a;
|
||||
a = "foo";
|
||||
a += " bar";
|
||||
// better would be:
|
||||
// StringBuilder a = new StringBuilder("foo");
|
||||
// a.append(" bar");
|
||||
String inefficientConcatenation() {
|
||||
String result = "";
|
||||
for (int i = 0; i < 10; i++) {
|
||||
// warning: this concatenation will create one new StringBuilder per iteration
|
||||
result += getStringFromSomeWhere(i);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
String efficientConcatenation() {
|
||||
// better would be to use one StringBuilder for the entire loop
|
||||
StringBuilder result = new StringBuilder();
|
||||
for (int i = 0; i < 10; i++) {
|
||||
result.append(getStringFromSomeWhere(i));
|
||||
}
|
||||
return result.toString();
|
||||
}
|
||||
}
|
||||
]]>
|
||||
|
@ -538,4 +538,34 @@ public class UseStringBufferForStringAppendsFP {
|
||||
}
|
||||
]]></code>
|
||||
</test-code>
|
||||
<test-code>
|
||||
<description>Test new rule example</description>
|
||||
<expected-problems>1</expected-problems>
|
||||
<expected-linenumbers>6</expected-linenumbers>
|
||||
<code><![CDATA[
|
||||
public class Foo {
|
||||
String inefficientConcatenation() {
|
||||
String result = "";
|
||||
for (int i = 0; i < 10; i++) {
|
||||
// warning: this concatenation will create one new StringBuilder per iteration
|
||||
result += getStringFromSomeWhere(i);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
String efficientConcatenation() {
|
||||
// better would be to use one StringBuilder for the entire loop
|
||||
StringBuilder result = new StringBuilder();
|
||||
for (int i = 0; i < 10; i++) {
|
||||
result.append(getStringFromSomeWhere(i));
|
||||
}
|
||||
return result.toString();
|
||||
}
|
||||
|
||||
String getStringFromSomeWhere(int i) {
|
||||
return "a" + i;
|
||||
}
|
||||
}
|
||||
]]></code>
|
||||
</test-code>
|
||||
</test-data>
|
||||
|
Reference in New Issue
Block a user