StringBuilder or StringBuffer As Class Field
ID |
java.stringbuilder_as_field |
Severity |
low |
Remediation Complexity |
medium |
Remediation Risk |
low |
Remediation Effort |
medium |
Resource |
Code Smell |
Language |
Java |
Tags |
code-style, concurrency |
Description
Reports StringBuilder or StringBuffer declared as a class field. These mutable builders are designed for short-lived, local use. Storing them as fields introduces shared mutable state and thread-safety concerns.
Rationale
A StringBuilder field persists across method calls, risking accidental content leakage between operations. If multiple threads access the field, data corruption occurs (StringBuilder is not synchronized). Even StringBuffer, while synchronized, is rarely the right choice for a field because contention on the monitor is a bottleneck.
// Bad - shared mutable state
class Formatter {
private StringBuilder sb = new StringBuilder();
public String format(String input) {
sb.append(input); // leaks data from prior calls
return sb.toString();
}
}
Remediation
Use a local StringBuilder inside each method that needs one. If building strings across multiple method calls, pass the builder as a parameter.
// Good - local scope, no leakage
class Formatter {
public String format(String input) {
StringBuilder sb = new StringBuilder();
sb.append(input);
return sb.toString();
}
}