Rule to detect Unused Public classes or methods


(Ankur) #1

I don’t see any rule which can detect unused public classes or methods. I understand that this is not easy to detect and when classes are referred outside the scope of source code being scanned, you will end up with lots of false positives.
But having such a rule can at least guide the team and they can decide whether the class/method is really unused or not.
Is this in the roadmap to provide such a rule ?

(Nicolas Harraudeau) #3

Hi @ankurja,

Thank you for your suggestion.
Similar rules exist for unused private methods and unused private fields.

We do not intend to create corresponding rules for public methods or classes as it would indeed raise many false positives. We focus on rules which raise as little false positives as possible, otherwise the rules are disabled by users.

If you believe that a public method or class is not used and you develop a library, I would recommend to deprecate it. It will raise warnings on code using the deprecated class or method, these warnings will also be visible in SonarQube.


(Jens Bannmann) #4

Hi @Nicolas,

I understand your reasoning. However, I am also interested in such a rule. My use case is as follows:

A project of about 50K lines consists of several dozens of modules and hundreds of packages. Only a handful of packages actually form an API in the sense of “should and can be consumed by other code bases”. Most public classes use this visibility solely in order to be accessible by other packages of the same project. The project itself lives in one Git repository and is built using a single Maven aggregator build. While Java 9 and its module system could be a solution, there are of course projects on Java <= 8, or projects who cannot move to Java modules. All in all, this means that a large portion of unused code is never detected by any tool.

What’s your take on this scenario? I think that a “unused public class/method” rule which can be activated selectively for folders of “public only inside the application” packages would be of great value in such projects (see Bean Validation should be enabled were a similar approach was taken for S5128). Would you perhaps be willing to specify a rule for this and accept an outside PR implementing it?

Also, could this be implemented (easily) within the current SonarJava architecture?

Note that my company uses SonarCloud and could therefore not install a custom rule.

Best regards,