``++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
[source,java]
----
public void doSomething(List<String> strings) {
StringBuilder sb = new StringBuilder(); // Noncompliant
sb.append("Got: ");
for (String str : strings) {
sb.append(str).append(", ");
// ...
}
}
----
=== Compliant solution
[source,java]
----
public void doSomething(List<String> strings) {
for (String str : strings) {
// ...
}
}
----
or
[source,java]
----
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.
Thanks [~ann.campbell.2]. I see one problem with this rule. We might pass the ``++StringBuilder++`` to a method, which internally calls ``++ToString++``, but at the declaring scope we won't know this. So if the ``++StringBuilder++`` is passed to a method we should not report on it.
=== on 15 Oct 2015, 11:32:13 Ann Campbell wrote:
Thanks [~tamas.vajk], I've added an explicit exception.