PMD Static Code Analysis for Apex

15th September, 2025

1. Why PMD?

Writing Apex code is easy. Writing good Apex code takes discipline. That’s where PMD comes in. It’s a static code analysis tool that helps:

  • πŸ” Detect code quality issues early
  • πŸ“ Enforce coding standards & best practices
  • 🧹 Reduce technical debt by finding error-prone patterns

2. Prerequisites

Before you start, make sure you’ve got these set up:

  • β˜• Java JDK (8 or later)
  • πŸ› οΈ PMD (static code analysis tool)
  • πŸ“¦ Apex PMD Plugin
  • πŸ’» Your Apex classes downloaded locally

3. Installing PMD

Download PMD from the official site, extract it, and configure environment variables.

# Windows example
Variable name: PMD_HOME
Variable value: C:\pmd

# Add to PATH
%PMD_HOME%\bin
          

Verify with:

pmd --version

4. Custom Ruleset

I used a rules.xml file located in /config/rules.xml. It checks:

  • Code style & formatting
  • Error-prone patterns
  • Performance issues
  • Apex best practices

5. Running PMD

Run PMD from your terminal inside the project root folder:

pmd check --dir "C:\path\to\classes" --rulesets "C:\path\to\rules.xml" --format csv
          

To generate a CSV report:

pmd check --dir "C:\path\to\classes" --rulesets "C:\path\to\rules.xml" --format csv --report-file pmd-report.csv
          

6. Report Output

The CSV report includes:

  • πŸ“„ File name
  • πŸ”’ Line number
  • βš–οΈ Rule violated
  • πŸ“ Description
  • πŸ”₯ Priority/Severity

Example:

"File","Line","Rule","Priority","Description"
"ServiceAppointmentHandler.cls","45","AvoidDmlStatementsInLoops","1","DML inside loops can cause governor limit issues."
          

Priority ranges from 1 (Critical) to 5 (Info). My run generated 1,037 entries across multiple Apex classes in the Gigaclear org!

7. Takeaways

βœ… PMD helps write cleaner Apex code.

βœ… Custom rulesets enforce Salesforce best practices.

βœ… Reports in CSV/XML/HTML make reviewing easy.

Integrating PMD in your workflow means fewer bugs, better performance, and a happier dev team πŸš€