Static Fields Should Be Final
ID |
java.constant_fields_must_be_final |
Severity |
info |
Remediation Complexity |
medium |
Remediation Risk |
low |
Remediation Effort |
medium |
Resource |
Code Smell |
Language |
Java |
Tags |
code-style |
Rationale
A mutable static field is effectively global mutable state: it is shared across all instances and all threads. This makes the code harder to reason about, complicates testing, and is a frequent source of concurrency bugs. If the field is intended as a constant, declaring it static final communicates intent clearly and prevents accidental modification.
// Bad -- mutable global state
static int MAX_RETRIES = 3;
static String DEFAULT_NAME = "admin";
Remediation
Add the final modifier. If the field truly needs to be mutable at runtime (e.g. a counter or configuration flag), consider using an AtomicInteger, a volatile field, or a proper configuration mechanism instead of bare mutable statics.
// Good -- immutable constant
static final int MAX_RETRIES = 3;
static final String DEFAULT_NAME = "admin";