SonarQube Duplicated Code
Copying and pasting code feels fast. The cost arrives later, when a bug fix must be repeated in every copy and someone forgets one. SonarQube finds duplicated blocks across files and shows their share of the project as a single percentage.
The Photocopy Picture
Imagine a company policy photocopied into ten folders. When the policy changes, someone must update ten copies. One missed folder leads to confusion. Code works the same way.
Before After
┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐
│ Copy A │ │ Copy B │ │ Caller A│ │ Caller B│
│ tax(...)│ │ tax(...)│ └────┬────┘ └────┬────┘
└─────────┘ └─────────┘ └─────┬─────┘
Fix needed twice ▼
┌─────────────┐
│ shared tax()│
└─────────────┘
Fix needed once
What SonarQube Counts
The detector looks for matching blocks of code that repeat inside one file or across files. A block qualifies when it holds a long enough run of tokens spread across several lines. The exact size differs by language, but small repeats such as a single line never count.
Key Measures
- Duplicated Lines is the number of lines inside repeated blocks.
- Duplicated Lines (%) is those lines divided by total lines.
- Duplicated Blocks is the count of repeated groups.
- Duplicated Files is the count of files that hold at least one repeat.
Why Duplication Hurts
- Bug fixes must reach every copy.
- Changes in one copy drift away from the others, creating strange differences.
- Projects grow larger without growing useful.
- Reviewers waste time reading the same logic twice.
Finding Duplicates in the Interface
- Open the project and select Measures.
- Choose Duplications.
- Sort files by duplicated lines.
- Click a file and open the duplication detail to view both locations side by side.
The Default Gate Limit
The built-in quality gate allows 3% duplicated lines on New Code. A change that pastes a large block triggers a failure, which pushes the developer to reuse existing code.
Removing Duplication
Extract a Function
Move the repeated logic into one function and call it from both places.
// Before
double a = price * qty * 1.18;
double b = cost * units * 1.18;
// After
double withTax(double rate, double amount) { return rate * amount * 1.18; }
Create a Base Class or Helper
When two classes share behavior, place the shared part in a common parent or utility class.
Use Configuration Instead of Copies
Two screens that differ only by labels often need one template plus data, not two files.
Excluding Files From Duplication Checks
Generated code and test fixtures repeat by nature. Exclude them so the number reflects human-written code.
sonar.cpd.exclusions=**/generated/**,**/*Dto.java
The property name uses the letters cpd, short for copy-paste detector.
When Duplication Is Acceptable
- Test code that repeats setup for readability.
- Code in two services that must evolve independently.
- Tiny repeats where an abstraction would confuse more than it helps.
Judgment matters. Extract only when the repeated logic truly represents one idea.
Prevention Habits
- Search the project before writing new utility code.
- Name shared helpers clearly so teammates find them.
- Review pull requests with duplication results visible.
- Run the IDE plugin to see warnings while typing.
Reading Trends
Open the Activity graph and select Duplications. A rising line signals that copy habits are growing. A flat or falling line shows healthy reuse.
A Practical Example
Two screens in an online store calculate shipping cost with nearly identical code. A developer fixes a rounding bug in one screen and forgets the other. Customers on the second screen pay the wrong amount for weeks. SonarQube would have flagged the duplicated block, and a shared function would have fixed both screens with one change. Duplication detection protects teams from this kind of silent split.
Review Routine
Open the duplications view once per sprint and look at the three largest blocks. Decide as a team whether to extract, accept, or exclude each one. Short, regular reviews keep the percentage low without a heavy cleanup project.
Quick Recap
Duplication multiplies maintenance work. Detect it with SonarQube, extract shared logic, exclude generated files, and keep new code under the gate limit.
