Using the Gradle Checkstyle and PMD Plugins

Reading Time: 2 minutes

Checkstyle is a library that analyzes a java project source code against a set of style rules to ensure that all contributions to a project adhere to a certain standard. This improves the readability of the code, decreases the time required to onboard new team members and improves the maintainability of the source code. PMD is a library that analyzes a java project source code against a set of designs and coding best practices rules and makes sure it’s generally designed well.

Image for post
[1]

Adding Checkstyle and PMD

lets configure the check style and PMD plugins by adding closures to the build.gradle file as follows.

plugins {
   id 'pmd'
   id 'checkstyle'
}
checkstyle {
   toolVersion = '6.11.2'
   config = rootProject.resources.text.fromFile('etc/checkstyle/checkstyle.xml')
   ignoreFailures = true
}
tasks.withType(Pmd){
   reports{
       xml.enabled=true
       html.enabled=true
   }
}
pmd {
   ruleSetConfig = rootProject.resources.text.fromFile('etc/pmd/pmd-rules.xml')
   pmdTest.enabled=false
   ignoreFailures = true
}

Where the checkstyle.xml and pmd-rules.xml files are sets of rules. Each of those rules is configurable to allow you to modify the rules. Now open the terminal and simply build the code using gradle clean build. You will then find the generated reports in the build/reports directory. Open the html files for both PMD and check style reports. You can see where you should refactor you code to meet the standards set in the rules files. Those reports also show which file and which line you should improve.

Conclusion

PMD sounds similar to check style. However, to maintain a separation of responsibilities, you should use check style rules for source code formatting only while PMD should be used for design standards and coding best practices.

References

[1] https://medium.com/@raveensr/how-to-add-checkstyle-and-findbugs-plugins-in-a-gradle-based-project-51759aa843be

Happy blogging!

blog-footer.jpg

Discover more from Knoldus Blogs

Subscribe now to keep reading and get access to the full archive.

Continue reading