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:
- Within a source file
- Across multiple files in a project
- Across multiple projects
Looking For Duplications
Add the Duplications widget (was Comments & Duplications prior to version 3.7) to your dashboard:
From there, you can drill down to the Duplications perspective in the component viewer:
How to read the example above:
- There is duplication among three blocks (shown to the left of the red box).
- Each block is 12 lines long. Note that because SonarQube's duplication detection mechanism is sophisticated enough to overlook whitespace differences, the number of lines will not always be the same from block to block.
- The first block starts at line 43 in in the file FindbugsVersion.
- The second block starts at line 40 in the file CheckstyleVersion. The icon to the right of the file name signifies that the file is located in another module or project.
- The third block starts at line 40 in the file PmdVersion. PmdVersion is also located in another module or project.
To display the source of a particular instance of a block, click on the file name.
To visualize the entire block of code, click on the Expand link.
Activating Cross Project Duplication Detection
Log in as a a System administrator, go to Settings > General Settings > General > Duplications and set the Cross project duplication detection property to true.
Run a new analysis on your projects to detect duplications with other projects.
- Always check for duplications in a file before modifying it. If there are any:
- Analyze those duplications and eliminate them by using inheritance or other suitable patterns (do this only if you have unit tests on the blocks to change)
- Or do not forget to replicate your changes wherever it is necessary on the duplicated blocks
- Use the Issues and Technical Debt mechanisms to help you monitor the cost and and track the remediation of this sin by editing your Quality Profiles to include the Duplicated Blocks rule from the Common Sonar repository.
See the following blog post: Manage Duplicated Code with Sonar.