javasonarqube

Where is the Sonar "duplicated code" here?


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


Solution

  • 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];
    }