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?
Asked
Active
Viewed 4.4k times
2 Answers
23
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];
}

Tunaki
- 132,869
- 46
- 340
- 423
-
1I do not know how Sonar can detect "duplicated logic" but the solution looks the right one. – John Donn Mar 05 '17 at 20:49
-
1Literals are ignored in copy paste detection. So if you "blank" int literals and string literals... the code is duplicated. – benzonico Mar 06 '17 at 09:30
-
2so complexity is preffered over any duplication by sonar's detection? – Eaton Emmerich Jun 15 '23 at 13:19
2
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

ΦXocę 웃 Пepeúpa ツ
- 47,427
- 17
- 69
- 97