Sub topic 1
What Code Analyzer does and why use it
This chapter assumes you know basic Apex, Salesforce DX project structure, and the sf command. Salesforce Code Analyzer is a static analysis tool. It examines source code without running it and reports patterns that may indicate bugs, security risks, performance problems, or maintainability issues.
A scan gives each finding a rule, engine, severity, file, and location. Use it during development to find problems early and in CI to check pull requests consistently.
Prerequisites
You need Salesforce CLI installed and authenticated as needed for your workflow. You also need a Salesforce DX project, commonly containing a force-app directory and sfdx-project.json.
The engines behind the rules
Code Analyzer combines engines that specialize in different checks:
- PMD checks Apex and other supported code for errors, risky patterns, and style problems.
- ESLint checks JavaScript and Lightning Web Components.
- RetireJS identifies vulnerable JavaScript dependencies.
- Regex finds text patterns that match configured expressions.
- CPD detects duplicated code.
- The graph engine, also called SFGE, follows data flow through Apex. It can detect how user-controlled data moves through operations, such as database queries. This differs from pattern-based checks because it analyzes relationships between statements.
A rule selector determines which rules run. Recommended is a practical starting set. You can also select an engine, category, tag, or named rule.
Installing the plugin
Install the Salesforce CLI plugin globally, then list its available rules:
npm install --global @salesforce/cli
sf plugins install code-analyzer
sf code-analyzer rules --rule-selector RecommendedThe rules command helps you discover rule names, engines, tags, and severities before choosing a scan policy.
Listing rules and choosing a rule selector
Start with Recommended for a broad review. Use a narrower selector when investigating a specific concern, such as PMD security rules:
sf code-analyzer rules --rule-selector pmd:SecuritySelectors affect which checks run, not which files are included. Choose a selector that matches the purpose of the scan. A local scan may use a broad set, while a focused CI job may use security rules or an approved rule list.
Exercise
Which engine should you investigate when a finding depends on how data moves through several Apex statements?
Show answer
The graph engine, SFGE, because it performs data-flow analysis.