Sonar CPD detecting blocks duplications

satheesh picture satheesh · Feb 13, 2013 · Viewed 11.4k times · Source

I have done so much analysis on how sonar cpd detects duplicate blocks.But I am not able to trigger out exactly what the process it takes to detect blocks or lines of code.Do that have any minimum number of lines.

For example if I am writing as below it is not detecting any code duplications even I repeat more that 20 times.

        System.out.println("this is good");
        System.out.println("this is good");

        System.out.println("this is good");
        System.out.println("this is good");

        System.out.println("this is good");

        System.out.println("this is good");

        System.out.println("this is good");

        System.out.println("this is good");

        System.out.println("this is good");

        System.out.println("this is good");

Later on I tried giving blocks duplications

     try
    {
    connection = null;
    }
    catch(Exception e){
        e.printStackTrace();
    }
    try
    {
    connection = null;
    }
    catch(Exception e){
        e.printStackTrace();
    }
    try{
    connection = null;
    }
    catch(Exception e){
        e.printStackTrace();
    }
    try{
    connection = null;
    }
    catch(Exception e){
        e.printStackTrace();
    }

Here it is considering as two block even though it has many blocks.

Please let me know the exact process followed in this duplication detection by sonar 3.4.1

In this http://docs.sonarsource.org/3.1/apidocs/src-html/org/sonar/plugins/cpd/SonarEngine.html

I found a constant block size as 10. But I am able to relate this in my observation.

Answer

András Tóth picture András Tóth · Feb 13, 2013

A block is the lines of code between balanced braces. The constant block size means that in the block there must be 10 Lines of code to match. So to have a duplication try this.

public void foo(){
//... 10 lines of code
}

private void bar(){
//.... the same 10 lines of code
}