Apex code analysis with PMD in VSCode

Introduction

Writing quality & well maintainable code is of utmost importance for any Software Developer. In today’s article we will cover the steps to do Apex code analysis with PMD in VSCode. By leveraging PMD, you can streamline your development process and create robust applications.

This article covers:

Step 1: Installation & Setup PMD

  • Visit the PMD website here.
  • Extract the zip installed in your system. Example: pmd-dist-7.0.0-rc4-bin
  • After extracting the zip, copy the bin path inside the extracted folder. Example: C:\pmd-dist-7.0.0-rc4-bin\pmd-bin-7.0.0-rc4\bin
  • Setup the Environment Variable by:
    • Open Environment Variable from control panel, edit PATH and add the complete location of bin folder.
    • Optionally, you can setup the path from command prompt by entering SET PATH=C:\pmd-dist-7.0.0-rc4-bin\pmd-bin-7.0.0-rc4\bin;%PATH%.

If you are facing issues to setup PMD, please read through the details document Step by Step guide to install and setup PMD for Apex.

Note: Setting up path from command prompt using SET PATH=C:\pmd-dist-7.0.0-rc4-bin\pmd-bin-7.0.0-rc4\bin;%PATH% will temporary set the path only for the current session, you will have to repeat the this again when session expires/ system restart.

Verify PMD is installed by entering pmd in the command prompt. you should see the response similar to screenshot below.

pmd command installation check
PMD installation verification in CLI

Step 2: Create a ruleset.xml file for code analysis in PMD

Open your notepad and copy paste the below xml code to get started, save the file as ruleset.xml. (You can name it anything you like)

<?xml version="1.0" encoding="UTF-8"?>
<ruleset xmlns="http://pmd.sourceforge.net/ruleset/2.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="Default ruleset used by the CodeClimate Engine for Salesforce.com Apex" xsi:schemaLocation="http://pmd.sourceforge.net/ruleset/2.0.0 https://pmd.sourceforge.io/ruleset_2_0_0.xsd">
    <description> Custom Rule Set </description>

    <rule ref="category/apex/bestpractices.xml" />
    <rule ref="category/apex/documentation.xml" />
    <rule ref="category/java/errorprone.xml/EmptyCatchBlock" />

    <!--excluding some rules -->
    <rule ref="category/apex/codestyle.xml">
	<exclude name="WhileLoopsMustUseBraces"/>  
        <exclude name="IfElseStmtsMustUseBraces"/>  
    </rule>

</ruleset>

Explanation

We won’t get deep into learning how to create your ruleset, but will give you an understanding of whats happening here.

In the rule set sample above, we mentioned the rules that we want our code to check for using <rule ref=”” /> tag. We can also mentioned rules that we want to ignore while running the static code analysis in pmd using <exclude name=”” /> tag.

pmd static code analyser

Read the PMD Documentation to learn more about creating rulesets.

Step 3: Install the PMD Extension in VSCode

Prerequisite

If you have not yet installed and setup VSCode, please go through Setup VSCode for Salesforce

Installing Apex PMD Extension in VSCode
Install Apex PMD extension in VSCode.

After you have successfully installed and setup vscode.

Click on Extensions icon in VSCode and then search for pmd. This will give you the list of available extensions with that name.

Select the Apex PMD option from the list of extensions, this will open the details about this extension. Click on the install button and wait for a while.

Step 4: Configure the ruleset.xml path in VSCode under PMD settings

In the next step, we are going to configure the ruleset.xml file in the VSCode. This is done to have better control over the set of rules under which we want to do static analysis of the code.

Settings in VSCode for Apex code analysis with PMD in VSCode
VSCode settings for PMD

Click on the Settings icon at the bottom left side of VSCode (as depicted in the screenshot above) and select Settings option. In the Settings screen, search for PMD and select Apex PMD Configuration.

There are a host of different configurations that your can do for PMD, but are going to discuss the few important ones.

PMD bin path configurations in VSCode
Configure PMD package root folder.

Configure Bin Path: Under Apex PMD: Pmd Bin Path section, add the root folder of the extract pmd package. This root folder should have a child bin folder.

PMD ruleset configurations in VSCode
Configure PMD Ruleset file location and action which will trigger PMD analysis.

Configure Ruleset for analysis: Under Apex PMD: Rulesets section, you can add the absolute path of the ruleset.xml file you created in previous steps.

Actions to Run PMD: You can also configure when to run PMD analysis on different actions taken on a code, like Save, Open or Change.

Step 5: In Action – Apex code analysis with PMD in VSCode

Now that we have completed all the steps to install and configure PMD for VSCode. Its time to see things in actions.

We are going to open an apex class in VSCode and see how well PMD is able to provide recommendations or suggestions to improve our code based on the rule setup in the ruleset.xml file.

Highlighting issues for Apex code analysis with PMD in VSCode Panel
List of PMD issues for the classes in the Panel

In the above screenshot, you can see that we have opening AccountData.cls. In the bottom panel under the PROBLEMS tab, we can see issues highlighted by PMD.

The issues highlighted by PMD are grouped together for a class. Each issues has a description and a hyperlink at the end. You can click on the hyperlink to open the PMD documentation to learn more about this problem and how to fix it.

On the top right corner of the VSCode, you can see a small section giving you a high-level view of the issues with the code in red and yellow colors.

Performing Apex code analysis with PMD in VSCode
PMD highlights syntax with issues in VSCode

PMD also highlights the code syntax, red or yellow underline, with potential problems. You can hover over the line of code to open a popup with details of the issues, potential fix and link to PMD documentation for the issue.

Conclusion

Performing code review on a huge code base can be a daunting tasks for the development team, which can take lot of effort and bandwidth. Doing Apex code analysis with PMD in VSCode can potentially reduce manual code review efforts and time, which can better utilized in completing backlog stories.

Using PMD doesn’t remove the manual effort required to structure the code, instead it highlights the most common vulnerability clogging the code. The development team still needs to review the effort to allocate resources/ time to fix issues.

The following comprehensive guide, will help you to successfully do Apex code analysis with PMD in VSCode, empowering you to enhance code quality, enforce coding standards, prevent bugs, and optimize performance.

Embrace PMD as an essential tool in your Salesforce development journey, ensuring the delivery of reliable and high-quality software solutions.

Feel free to copy paste the sample commands above and play around. Don’t forget to subscribe to our newsletter for more Salesforce development tips.

If you have any issues or suggestions, please feel free to use the comment section below.

One Comment