Some will argue that Duplication is the worst coding sin because it perpetuates all the others. For instance, copying and pasting a block of code duplicates its Bugs and Potential Bugs, its Coding Standards Breaches, and so on. It's a meta-sin, if you will.

To help you detect and eliminate duplication, SonarQube uses its own copy/paste detection engine, which can detect duplications:

SonarQube allows to detect "Type 2" duplications which means :  structurally/syntactically identical fragments except for variations in literals and comments. A piece of code is considered as duplicated as soon as there are at least 100 successive and duplicated tokens (can be overridden with property sonar.cpd.${language}.minimumTokens) spread on at least 10 lines of code (can be overridden with property sonar.cpd.${language}.minimumLines). For Java projects, the duplication detection mechanism behaves slightly differently as a piece of code is considered as duplicated as soon as there is the same sequence of 10 successive statements whatever is the number of tokens and lines.

Looking For Duplications

Add the Duplications widget to your dashboard:

From there, you end up in the component viewer:

To display the source of a particular instance of a block, click on the file name.

Activating Cross Module and Cross Project Duplication Detection

By default, the scope of duplication detection is the project for standard projects and the module for multi-module projects. To detect duplications between the modules of your project and between the different projects analyzed on your SonarQube platform, log in as a a System administrator, go to Settings > General Settings > General > Duplications and set the Cross project duplication detection property to true. Then run another analysis on your projects. You also have the option of setting this at the project level: Configuration > General > Duplications.


Best Practices

Related Topics

See the following blog post: Manage Duplicated Code with Sonar.