Detect Dead Code and Calls to Deprecated Methods with Sonar Squid

by freddy mallet|

    Up to version 2.1, Sonar was relying only on external coding rules engines such as Checkstyle, PMD and Findbugs to report violations on Java applications. But since version 2.1, Sonar also provides its own rules engine to work on Java dependencies. This rules engine is based on Squid and three rules are currently available :


    (sonar-squid-rule-engine)

    Squid provides an easy to use visitor pattern to be able to visit dependencies between methods, fields, classes and packages. This visitor pattern has been used in Sonar 2.0 to calculate Object Oriented metrics like LCOM4, RFC, DIT, NOC, ... and has been reused in Sonar 2.1 to implement this new rules engine.

    Here is a description of the three new rules :

    • Use of deprecated method : Once deprecated, a method should no longer be used as it means that the method might be removed one day; it might also mean its usage is inefficient or does not enable to benefit from certain features. Using a deprecated method is a sort of technical debt that must be repaid earlier rather than later. The rule detects calls to deprecated methods not only inside but also outside the project. It means that you can track usage of deprecated methods on Java API or any other external libraries. Here is an example of violation :
    • Unused protected method or Unused private method : Protected or private methods that are never used by any classes in the same project are strongly suspected to be dead code. Dead code means unnecessary, inoperative code that should be removed. This helps in maintenance by decreasing the maintained code size, making it easier to understand the program. Protected methods that override a method from a parent class are not considered as dead code as those methods are most often used through polymorphism.



    To support those new functionality, a new Open Source library called sonar-check-api has been added in the Sonar toolbox. This library offers a mechanism to describe the rule : title, description, default priority, ISO category... For Checkstyle, PMD and Findbugs, an XML file is used to provide such description but this library allows use of java annotations to embed the description inside the rule. Here is an example of use with the new "Use of deprecated method" rule :




    Have fun with those three new rules while waiting for new ones like a rule to define the architecture layering :)