StringBuffer
and StringBuilder
instances that are append
ed but never toString
ed needlessly
clutter the code, and worse are a drag on performance. Either they should be removed, or the missing toString
call added.
Noncompliant code example
public void doSomething(List<String> strings) {
StringBuilder sb = new StringBuilder(); // Noncompliant
sb.append("Got: ");
for (String str : strings) {
sb.append(str).append(", ");
// ...
}
}
Compliant solution
public void doSomething(List<String> strings) {
for (String str : strings) {
// ...
}
}
or
public void doSomething(List<String> strings) {
StringBuilder sb = new StringBuilder();
sb.append("Got: ");
for (String str : strings) {
sb.append(str).append(", ");
// ...
}
LOGGER.info(sb.toString);
}
Exceptions
This rule ignores StringBuffer
s and StringBuilder
s that are passed as method arguments on the grounds that they are
likely toString
ed there.