toString() or clone() Returns Null
ID |
java.tostring_clone_returns_null |
Severity |
high |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Reliability |
Language |
Java |
Tags |
clone, reliability |
Description
Reports a toString() or clone() method that explicitly returns null instead of a real result.
Rationale
toString() is expected to hand back a string — possibly empty, never absent — and clone() is expected to hand back a copy of the receiver. Returning null from either breaks that expectation and pushes the failure onto the caller: string concatenation, logging, and debuggers all call toString() implicitly and will throw NullPointerException the moment they try to use the result.
// Bad -- caller gets a NullPointerException instead of a string
@Override
public String toString() {
if (items.isEmpty()) {
return null;
}
return String.join(", ", items);
}