Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where is the Sonar "duplicated code" here?

Tags:

java

sonarqube

I just run sonar scanner on the sample Sonar project. It gives me the message that there is "duplicated code on lines 7-20". Can anyone explain this?

enter image description here

like image 587
John Donn Avatar asked Mar 05 '17 20:03

John Donn


People also ask

Where is duplicate code in SonarQube?

SonarQube shows you all the duplications metrics on a project, package, or class basis. Further, you can use the Duplications tab in the file detail view to see the location of a duplication in a class.

How do I stop duplicate lines in SonarQube?

However, you can exclude all HTML files or only selected files from the Copy Paste Detection (CPD). To do so, you can either ignore files in the SonarQube UI under General Settings > Analysis Scope > Duplications using e.g. **/*.


2 Answers

SonarQube is telling you that this portion of the code contains duplicated logic. This doesn't necessarily mean that the code itself is copy-pasted, but that, conceptually, the exact same thing is happening at multiple places. In this case, the logic of returning a String value with regard to the int value is clearly repeated.

A simple solution here:

String[] array = { "One", "Two", "Three", "Four", "Five", "Six" };
if (i >= 1 && i <= array.length) {
    return array[i - 1];
}
like image 146
Tunaki Avatar answered Oct 10 '22 11:10

Tunaki


SonarRules for Java projects:

A piece of code is considered as duplicated as soon as there is the same sequence of 10 successive statements whatever the number of tokens and lines. This threshold cannot be overridden.

You need to modify that multiple if return sections

like image 33
ΦXocę 웃 Пepeúpa ツ Avatar answered Oct 10 '22 12:10

ΦXocę 웃 Пepeúpa ツ