Duplicate String Literals

ID

java.duplicate_string_literals

Severity

low

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.

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

minOccurrences

3

Minimum repetitions inside the class to flag.

minLength

5

Minimum literal length. Shorter strings (like ",", "0") are rarely worth constantising.