Fix #3374 - UseStringBufferForStringAppends: Wrong example in documentation

This commit is contained in:
Clément Fournier
2022-02-12 19:03:31 +01:00
parent ee1001a009
commit 962793cd54
2 changed files with 46 additions and 7 deletions

View File

@ -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();
}
}
]]>

View File

@ -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>