PMD is a well known Static code analyzer for Java and many other languages. It also supports Salesforce Apex as well.
Source code analysis is important during development cycle to point out weaknesses in code and to improve overall quality. Examples are:
- Code Complexity Measures (e.g. Lines of Code, Nesting Level, Code Clones)
- Dynamic Related Measures (e.g. Code Coverage, Bugs per Line of Code, Feature Usage)
For Salesforce Apex, the freeware PMD is a recommended tool to carry out Static Code Analysis. It provides an easy to use Plug-in for Eclipse and comes with a prebuilt rule set which is deployable right after installation:
- ApexUnit: These rules deal with different problems that can occur with Apex unit tests. (Rules: ApexUnitTestClassShouldHaveAsserts, ApexUnitTestShouldNotUseSeeAllDataTrue)
- Braces: The Braces ruleset contains rules regarding the use and placement of braces. (Rules: IfStmtsMustUseBraces, WhileLoopsMustUseBraces, IfElseStmtsMustUseBraces, ForLoopsMustUseBraces)
- Complexity: The Complexity ruleset contains rules that find problems related to code size or complexity. (Rules: AvoidDeeplyNestedIfStmts, ExcessiveParameterList, ExcessiveClassLength, NcssMethodCount, NcssTypeCount, NcssConstructorCount, StdCyclomaticComplexity, TooManyFields, ExcessivePublicCount)
- Performance: The Performance ruleset contains a collection of good practices which should be followed. (Rules: AvoidSoqlInLoops, AvoidDmlStatementsInLoops)
General information on PMD and the rules available for APEX:
- PMD Homepage: https://pmd.github.io/pmd-5.5.2/index.html
- PMD Apex Rulesets: https://pmd.github.io/pmd-5.5.2/pmd-apex/index.html
- PMD Installation guidance for Mac: http://macappstore.org/pmd/
- PMD Installation for Eclipse: http://pmd.sourceforge.net/eclipse/
There are multiple ways to use PMD in Salesforce Apex code, however this blog will focus on #1 to set-up standalone static code analysis in Eclipse
- We can run static code analysis standalone
- It can be part of ANT build to generate error reports
- Jenkins can use it to generate nice report around code quality
- Eclipse can use it as a plug-in to generate report
Steps to be followed during Installation and set-up PMD in Eclipse:
- In Eclipse, click on Help -> Install New Software.
- Click on Add.
- Enter the following:
- Name: PMD
- URL: https://dl.bintray.com/pmd/pmd-eclipse-plugin/updates/
and click OK.
- You should see PMD for Eclipse 4. Select the checkbox next to it and click Next >.
- You’ll need to accept the license and confirm you want to install a plugin that is not digitally signed. Go ahead and install it anyway.
- Restart eclipse.
Right click on project -> Property -> Select PMD
It’ll show you the code violation.