Why does EK9 reject repeated literal values?
← Code Quality · Ref: Q800
EK9 raises E11065 when the same literal value appears 3 or more times in a file. Repeated literals are a maintenance liability.
WHY REJECTED
When a literal needs to change, every occurrence must be found and updated. Research (Bettenburg & Shang, 2010) found that ~50% of changes to duplicated code are inconsistent - only some instances get updated.
THRESHOLDS
- 3+ occurrences in a single file: error
- 4+ occurrences across files in the same module: error
FIX: EXTRACT TO CONSTANT OR VARIABLE
//Before: repeated literal stdout.println("processing") stdout.println("processing") stdout.println("processing")
//After: named constant statusMsg <- "processing" stdout.println(statusMsg) stdout.println(statusMsg) stdout.println(statusMsg)
See Q799 for boolean argument naming. See Q777 for discarded returns.
Example
defines module qa.codequality.repeatedliteral defines program MagicLiteralDemo() stdout <- Stdout() statusMsg <- "processing" stdout.println(statusMsg) stdout.println(statusMsg) stdout.println(statusMsg)
Common mistakes
E11065 — The same literal 'processing' appears 3 times in the file. Extract it to a named variable or constant to avoid maintenance errors when the value needs to change. See ek9 -h E11065 for details.
Incorrect:
stdout.println("processing") stdout.println("processing") stdout.println("processing")
Correct:
statusMsg <- "processing" stdout.println(statusMsg) stdout.println(statusMsg) stdout.println(statusMsg)
Other ways to ask this
- What triggers E11065 repeated magic literal?
- How many times can I use the same string literal?
- Why must repeated values be extracted to constants?
Coming from another language?
Java: no compiler detection, relies on SonarQube S1192 or PMD. Python: no detection, relies on pylint. Rust: no detection for repeated literals. Kotlin: no compiler detection. Go: no detection. EK9: compile-time error E11065 at threshold of 3 per file or 4 per module.
Keywords: constant, maintenance, extract, literal, duplication, magic, E11065, repeated