SonarQube Code Duplicates

Sometimes you need to copy code between different projects for several reasons. It is required that the same class has to be in both projects e.g. a class that is compiled with different frameworks. But this has a negative impact on code analysis results regarding code duplicates. So let’s take an analysis result of a sample project.

If you add files to Visual Studio, you have two options to add a file to a project. Either you can add a file as a copy (`Add`), which means a copy of the file is added to the project folder structure. Adding the file with the option `Add as Link`, the file is just referenced from the selected location but not copied anywhere.

The first analysis shows a set of files that were added to a sample project A. The code has 367 lines of code but no duplicated lines. It comes to a difference if you add the same files to a second project B using the `Add` functionality. The second analysis shows the results. This shows the code in both files as a duplicated line. This means as a conclusion, copying ten lines of code results in 20 duplicated lines of code.

Now it comes to the question, what happens if the file is added using `Add as Link` functionality. Project B now removed the copies of the files and adds the files from project A as a link. The third analysis shows that the lines of code back to 367 lines and no duplicates. This would be the preferred result for these copied files.

But what about the analysis results four, five and six? Well, analysis four links the files from a folder, that is not located in the solution folder e.g. a shared code solution from a different repository. SonarQube does not count files from outer-solution folders. Analysis number five uses shared files that are in a shared folder, that is not located underneath project A or project B. The analysis is a test if SonarQube analyses files that are not referenced by any project e.g. stale files. They are not.

In a conclusion: Duplicated lines because of copied files can be removed by adding the files as reference. It is recommended to use a separate folder that contains the shared files instead of letting project B include files directly from project A.




Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert