Software development is difficult to get right. Even the best developers struggle to avoid defects and consistently produce high-quality work. Resolving those defects gets more expensive the longer they remain in the code. Studies show a 500 – 2,000% cost reduction in fixing a defect during coding, as opposed to in production.
“Static analysis” is a process that automatically identifies potential defects in code. PMD is a free static analysis tool that works with Apex code, will help you find bugs, and make you a better coder!
This is the first in a series of posts on how to utilize PMD within your Visual Studio Code projects.
Installation
- Download the latest version of PMD
- Extract the zip file to a convenient location. The default folder name will be something like “pmd-bin-6.22.0”, but we like to shorten that to “pmd”. Our preference is to put this folder inside a “Tools” folder, which is a sibling of project folders.
- Open your Salesforce project in Visual Studio Code.
- Navigate to the Extensions panel (View | Extensions), search for “Apex PMD” by Charlie Jonas, and click “Install.” See Charlie’s GitHub repository for more information on his plugin.
Configuration
- In Settings (Code | Preferences | Settings), search for “PMD” and set “Pmd Bin Path” to the location of the folder you created in step 2.
- Adjust any other settings as desired.
- Priority thresholds: which issues will be reported as errors and which as warnings.
- Run on File Open / Run on File Save: these settings dictate when PMD will run on a file.
- Output options: specify whether you’d like to see warning and error output.
- In a later post, we’ll talk about rulesets and how to customize them.
Scanning Your Code
Now that PMD is installed and configured, running a scan will be simple. By default, a file will be scanned when you open or save it. In addition, there are a couple of ways to manually scan:
- In the Command Palette (View | Command Palette), choose “Apex Static Analysis: On File” or “Apex Static Analysis: On Workspace”
Checking the results
PMD posts its results to the Problems panel (View | Problems). Click a row to navigate directly to the line with the problem. Stay tuned for a later post where we’ll talk about the meanings of various warnings and how to resolve or silence them.
That’s it for now. Stay safe and happy coding!