Duplicate String Literals
ID |
java.duplicate_string_literals |
Severity |
high |
Remediation Complexity |
medium |
Remediation Risk |
low |
Remediation Effort |
medium |
Resource |
Code Smell |
Language |
Java |
Tags |
code-style, duplication |
Description
Reports string literals that appear the same value minOccurrences times or more inside a single class. Repeated literals should be extracted to a static final constant so a rename touches one place instead of many.
The finding is raised once per literal, at its first occurrence, and names the literal. The repetition is one fact about the class, not one fact per copy: reporting every occurrence turned a literal used six times into six identical findings that say the same thing and are fixed by the same edit.
A literal inside an array initializer is not counted. A lookup table — JAVA_KEYWORDS,
CSHARP_KEYWORDS, GO_KEYWORDS — repeats "class" and "catch" because several languages share
keywords; that is data, not a magic value threaded through logic, and extracting it to a constant
is not followable advice.
Rationale
Copies of the same literal are an open invitation to an inconsistency bug: one copy gets updated, the others don’t, and the mismatch lurks until a user hits it. Extracting to a constant also makes the string’s meaning explicit — MAX_RETRIES_EXCEEDED reads better than the raw "max_retries_exceeded" scattered across call sites.
The rule excludes literals inside annotation arguments (they are part of the configuration DSL, not executable code) and entire test classes (assertion fixtures legitimately repeat literals).
Remediation
Replace repeated literals with a constant.
// Before
public void a() { log("error-message"); }
public void b() { alert("error-message"); }
public void c() { notify("error-message"); }
// After
private static final String ERROR_MESSAGE = "error-message";
public void a() { log(ERROR_MESSAGE); }
public void b() { alert(ERROR_MESSAGE); }
public void c() { notify(ERROR_MESSAGE); }
Configuration
| Property | Default | Description |
|---|---|---|
|
|
Minimum repetitions inside the class to flag. |
|
|
Minimum literal length. Shorter strings (like |