Consider a situation when you have to solve a problem to get a particular task done and you start writing your apex code for that. After some time, you finally completed your code. You analyzed it using a free tool and it is telling you that here are the points where your code is not following the standards or it is not properly optimized. Now what ? Your next step will be asking your friends or take the help of Trailblazer Community to make your code perfect and optimized. As a result, it not only improved your code performance but also improved your skills. So, that in future if somebody looks at your code, He/She will be impressed by looking at your perfect style of writing code. Great !
What is PMD ?
PMD basically stands for Programming Mistake Detector. It is a source code analyzer that finds common mistakes in your code like:- unused variables, if-else statements without braces, naming conventions of methods, soql in loops and many more. It also includes CPD which stands for Copy/Paste Detector which finds duplicate code in your files and make you aware so that you can improve to make your code reusable.
Setting up PMD
You can download the latest version of PMD as a zip file from the PMD Homepage by clicking the download link or you can scroll down to the downloads section and download any other version from there. Currently, the latest version is 6.0.0 which was released yesterday. You can download it directly here.
After downloading the zip file you have to extract it and it will give you two folders namely bin and lib apart from a LICENSE file. I am currently using a windows operating system so going to tell you the commands according to that. If you are using a Linux/Unix OS you can read from here and then follow the similar commands according to your OS from the getting started page.
In the bin folder, we get a number of batch files out of which - pmd.bat and cpd.bat files are the one which we'll be mainly using for using pmd. As PMD is a command line tool, so if you want to use it like from anywhere on your system, I suggest you to add pmd bin to your system path in the environment variables so that it can be accessed from anywhere on your system. That's all for setting up let's learn how to use PMD.
Analyzing code using PMD
Now you have installed PMD and you want to analyze your code. PMD allows you to analyze code written in a number of languages like:- java, javascript, xml, apex etc. We'll mainly focus on the apex code here. So here is the general command syntax to analyze the apex class or a directory consisting of a number of classes as follows:-
The release 6.0.0 is the latest and is a major release so even if you are already using PMD, this release consists of a number of changes that you must be aware of. Even the apex rules categorization is updated and the old rule-sets like:- Braces, Complexity is deprecated now. You can know about the latest apex rules in the current release of PMD here. The table of contents present on this page have the same name as the xml files present in the pmd library implementing the rules under that name. Below is the example command using the default rules already present in pmd library for apex. It is using the design.xml rule file under the apex category following the name of the rule that you want to check.You can run the command without any rule name to use all the rules present in that xml file.
This command is checking that in all the apex classes present in the classes folder. If there is any class which is using methods with excessive parameters. The excessive parameter rule is present in the standard library and you can view it here. So, when I run this command as I have set the format as html and the output file is named output.html, I get the file named output.html in the current directory where the command is executed as I have not given any path for output.html but you can keep a separate path for output report files.
The report created by pmd for me is an html file which looks like this:-
The report gives you the file name with path, the line number that consists of error as well as the problem which is the direct link to the original doc where the sample error code is there to which your code resemble leading to error. When I opened my test.cls then this was the code snippet giving me error:-
As you can see this method consists of a number of parameters whereas it is preffered that you use less parameters in your method. So this is how you can use pmd with some general standard rules defined in the library to check whether your code quality is good or not.
Apart from people working as a developer or admin, if you are a technical architect or even the owner of your company. Then obviously you want people working under you to write perfect code and maybe follow only a bunch of standard rules that you think are most important. Don't worry PMD has taken care of that too.
You can make your own rule file in which you can define a bunch of standard rules and then distribute it to other developers so that they must follow the standards while writing code.
You can see in the file below that I am using three common ways by which you can add rules to your rule-set file.
This command is checking that in all the apex classes present in the classes folder. If there is any class which is using methods with excessive parameters. The excessive parameter rule is present in the standard library and you can view it here. So, when I run this command as I have set the format as html and the output file is named output.html, I get the file named output.html in the current directory where the command is executed as I have not given any path for output.html but you can keep a separate path for output report files.
The report created by pmd for me is an html file which looks like this:-
As you can see this method consists of a number of parameters whereas it is preffered that you use less parameters in your method. So this is how you can use pmd with some general standard rules defined in the library to check whether your code quality is good or not.
Apart from people working as a developer or admin, if you are a technical architect or even the owner of your company. Then obviously you want people working under you to write perfect code and maybe follow only a bunch of standard rules that you think are most important. Don't worry PMD has taken care of that too.
You can make your own rule file in which you can define a bunch of standard rules and then distribute it to other developers so that they must follow the standards while writing code.
You can see in the file below that I am using three common ways by which you can add rules to your rule-set file.
- By using a single rule from a rule-set.
- By using full rule-set present in the library.
- By using full rule-set but excluding some of the rules from it.
In this way, you can make your own rule-set file and you can use that file as follows:-
I have set the minimum tokens to 5 and specifically used my test.cls as I have added a lot of duplicate code in that. So, you can see the output from cpd below:-
As you can see above, I have duplicated System.log('function with excessive parameters'); and also the doWork() by writing it as doMoreWork() with multiple integers, as the number of minimum tokens I specified in cpd command are very less i.e. 5 so cpd is reporting it as duplicate code.
Even if you don't like to use command line, PMD has made a cpdgui that you can use to find duplicate code in your directory and you can even simply export your report to text, xml or csv formats.
Just go to the command line into your bin folder and type cpdgui.bat and you will see an application like this:-
In the application, select the folder in which your classes are present and change value in report duplicate chunks larger than field the default value is 75. It is similar to minimum tokens you have in cmd. Select the language as apex and click on go. You have a report like the one shown below and you have the option to export that too.
If you want to learn more about CPD you can checkout the docs here. So, now you learned how you can analyze your code usind PMD Source Code Analyzer and also how you can detect duplicate code using CPD - Copy Paste Detector tool from PMD.
Try the above command by copying the rule-set file given above or making your own rule-set file and start analyzing your code.
CPD - Copy/Paste Detector
CPD is another feature of PMD that you can use to analyze the re-usability implemented in your code. It scans your files and detects duplicate code for you. The general syntax for the CPD command is as follows:-
Below is the example command for the above syntax that I used to find duplicate code in my files:-I have set the minimum tokens to 5 and specifically used my test.cls as I have added a lot of duplicate code in that. So, you can see the output from cpd below:-
As you can see above, I have duplicated System.log('function with excessive parameters'); and also the doWork() by writing it as doMoreWork() with multiple integers, as the number of minimum tokens I specified in cpd command are very less i.e. 5 so cpd is reporting it as duplicate code.
Even if you don't like to use command line, PMD has made a cpdgui that you can use to find duplicate code in your directory and you can even simply export your report to text, xml or csv formats.
Just go to the command line into your bin folder and type cpdgui.bat and you will see an application like this:-
In the application, select the folder in which your classes are present and change value in report duplicate chunks larger than field the default value is 75. It is similar to minimum tokens you have in cmd. Select the language as apex and click on go. You have a report like the one shown below and you have the option to export that too.
If you want to learn more about CPD you can checkout the docs here. So, now you learned how you can analyze your code usind PMD Source Code Analyzer and also how you can detect duplicate code using CPD - Copy Paste Detector tool from PMD.
Nice Article!! I am going to try this tool. Wanted to check if it will detect unused methods/code as well?
ReplyDeleteThanks Sushil. PMD has a feature to detect unused code as well as far I know it is not available for apex right now. I have used it for java -
Deletehttp://pmd.sourceforge.net/pmd-4.3.0/rules/unusedcode.html . But always have an option to make a custom rule or maybe we have to wait for next release for this.
Very nicely written .
ReplyDeleteIs it IDE dependent ? Is it use only with eclipse ?
Hi,
DeleteAs you can use it simply with command line, therefore it's not IDE dependent in any way. Happy to see that you liked the post. Do share it in your network too :-)
Hey, does it need the entire source files to run? because of dependency? because I just randomly took an apex file from my application and tried to run but its giving an exception. Below is the command and the output, appreciate a response.
ReplyDeleteC:\pmd-bin-6.12.0\bin>pmd.bat -d C:\DCOM_Language_Preference_Update.apxc -R rulesets/java/quickstart.xml -f text
Mar 07, 2019 7:18:12 PM net.sourceforge.pmd.RuleSetFactory parseRuleReferenceNode
WARNING: Discontinue using Rule name category/java/multithreading.xml/UnsynchronizedStaticDateFormatter as it is scheduled for removal from PMD. PMD 7.0.0 will remove support for this Rule.
Mar 07, 2019 7:18:12 PM net.sourceforge.pmd.PMD processFiles
WARNING: This analysis could be faster, please consider using Incremental Analysis: https://pmd.github.io/pmd-6.12.0/pmd_userdocs_incremental_analysis.html
C:\DCOM_Language_Preference_Update.apxc - PMDException: Error while parsing C:\DCOM_Language_Preference_Update.apxc
Thanks
Manju
Hi Manju,
DeleteI think you're trying to use a java ruleset on an apex file and that's why pmd is not able to parse your file and giving error. Can you verify you're using the correct ruleset ?
Hi does it support salesforce lightning and LWC components?
ReplyDeleteHi Anuj, I don't think so. PMD doesn't support lighting yet.
Delete