Repeated Cast of Same Object
ID |
java.repeated_cast_same_object |
Severity |
low |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Efficiency |
Language |
Java |
Tags |
efficiency |
Rationale
Casting the same object to the same type multiple times is redundant. Each cast adds visual noise and, depending on the JIT compiler, may incur a small runtime cost for the type check. More importantly, repeated casts are a readability problem: they signal that the code would benefit from a local variable holding the cast result.
// Bad -- repeated cast
String a = ((String) obj).trim();
String b = ((String) obj).toLowerCase();
Remediation
Cast once, store the result in a local variable, and reuse it.
// Good -- cast once, reuse
String s = (String) obj;
String a = s.trim();
String b = s.toLowerCase();