Sub topic 1
What Code Analyzer does and why use it
What it is
Salesforce Code Analyzer is a static analysis tool for Salesforce projects. Static analysis means it reads your source files and looks for problems without deploying or running anything. You run it from the Salesforce CLI with the sf code-analyzer commands, and it reports every place where your code breaks a rule.
Code Analyzer does not do the checking itself. It is a single front end over several existing analysis tools, called engines. Each engine knows how to inspect certain kinds of files:
- Apex classes and triggers
- Lightning Web Components and other JavaScript
- Flows
- Third-party libraries
Code Analyzer runs the engines you select, collects their findings, and presents them in one format with one severity scale.
This chapter covers what the tool checks, where it fits in a development workflow, and what to expect from a scan. Later chapters cover installing it and running scans in detail.
Prerequisites
This chapter assumes you have:
- Basic Apex, plus either Lightning Web Components or JavaScript.
- The Salesforce CLI (
sf) installed, and you are comfortable running it from a terminal. - A Salesforce DX project layout, with a
force-appfolder and ansfdx-project.jsonfile. - Familiarity with Git and a basic CI workflow, such as a pull request that triggers a pipeline.
You do not need a Salesforce org to follow this chapter. Code Analyzer reads local files and never connects to an org.
What kinds of problems it finds
The rules cover several categories. Each category matters for a different reason.
- Performance and governor limits. Salesforce limits how many queries, DML statements, and CPU milliseconds one transaction can use. Patterns such as a DML statement inside a loop can exceed those limits. Code Analyzer flags these patterns before they fail in production.
- Security. Rules look for risks such as SOQL built from unescaped strings, hard-coded credentials, and unsafe use of
innerHTMLin JavaScript. - Best practices and design. Examples are overly complex methods, empty catch blocks, and leftover
System.debugcalls. - Code style and consistency. Naming and formatting rules keep a team's code uniform.
- Dependencies. Rules can flag known-vulnerable JavaScript libraries that you ship in static resources.
- Duplication. Copy-paste detection finds large blocks of repeated code.
Here is a small Apex class that Code Analyzer's PMD rules flag. The update statement sits inside a for loop, so it runs one DML statement per account:
public class AccountUpdater {
public static void renameAll(List<Account> accounts) {
for (Account acc : accounts) {
acc.Name = acc.Name + ' Inc.';
update acc;
}
}
}With a small list this works. With a bulk load of more than 150 records, the transaction hits the DML statement limit and fails. A unit test with three records will not catch that, but a static scan will, because the pattern is visible in the source. The fix is to modify the records in the loop and call update accounts; once after it.
Where it fits in the workflow
Code Analyzer is most useful when it runs at several points, each catching problems at a different cost.
- In the editor. Developers can see findings while writing code, so fixes cost seconds.
- In a terminal before committing.
sf code-analyzer rungives a quick check of the files you changed. - In CI on every pull request. The pipeline fails when serious violations appear, so they do not reach the main branch.
- Periodically across the whole codebase. A full scan shows accumulated technical debt and tells you where to focus cleanup.
Why use it instead of relying on tests and reviews
Unit tests and code review are necessary, but each has gaps that static analysis fills.
| Approach | Strength | Gap |
|---|---|---|
| Unit tests | Verify behavior for the inputs you wrote | Do not exercise patterns that only fail at bulk volume or under attack |
| Code review | Catches design and intent problems | Reviewers miss repetitive issues and vary in what they notice |
| Code Analyzer | Applies the same rules to every file, every time | Reports only what its rules describe, and some findings are false positives |
Static analysis is consistent and cheap to repeat. It gives reviewers a head start, because they no longer have to hunt for mechanical problems and can spend their attention on design.
What a scan produces
Every finding, called a violation, carries the same core fields regardless of which engine produced it:
- Rule name. The identifier of the rule that was broken, such as
AvoidDebugStatements. - Engine. The tool that owns the rule, such as
pmdoreslint. - Severity. A number from 1 to 5, where 1 is Critical, 2 is High, 3 is Moderate, 4 is Low, and 5 is Info.
- Location. The file, line, and column where the problem starts.
- Message and tags. A short description of the problem, plus tags such as
SecurityorPerformancethat you can use to group rules.
The common scale is one of the main benefits. PMD and ESLint each have their own notion of priority. Code Analyzer maps them onto one scale, so a single threshold can gate a build across all engines. Later chapters show how to read results and how to fail a run at a chosen severity.
The engines in brief
Which engine produces a finding depends on the file type:
| Engine | What it examines |
|---|---|
| PMD | Apex and Visualforce source |
| ESLint | JavaScript and Lightning Web Components |
| RetireJS | Known-vulnerable JavaScript libraries |
| Regex | Custom text patterns defined by simple regular expressions |
| Flow | Salesforce Flow metadata |
| CPD | Duplicated blocks of code |
A separate engine, the graph engine (SFGE), follows data flow across methods and files. It is slower and is used for deeper security checks. The next chapter covers each engine in more detail.
Limits to keep in mind
Static analysis is useful, but it has limits you should know before you rely on it.
- False positives happen. A rule may flag code that is intentional and safe. You handle these with an inline suppression and a written reason, or with configuration. A later chapter covers this.
- False negatives happen too. A clean scan does not prove the code is correct or secure. It only means no enabled rule matched.
- Noise discourages teams. Turning on every rule for a large legacy codebase produces thousands of findings. The usual approach is to start with the Recommended rule set and raise the bar over time.
- It is not a substitute for tests. Code Analyzer never runs your code, so it cannot confirm that your logic does the right thing.
A first look at the commands
You will use three commands most often. This chapter only previews them. Installation and details follow in later chapters.
npm install --global @salesforce/cli
sf plugins install code-analyzer
sf code-analyzer rules --rule-selector RecommendedThe first line installs the Salesforce CLI. The second adds the Code Analyzer plugin. The third lists the rules in the Recommended set, which is the curated default selection for typical Salesforce projects. Running a scan then uses a similar flag pattern with sf code-analyzer run.
Key takeaways
- Code Analyzer is a single command-line front end over several analysis engines, and it reads your source without running it.
- It finds performance, security, best-practice, style, dependency, and duplication problems.
- All findings share one format and one 1 to 5 severity scale, so a single rule of thumb can gate a build.
- It complements unit tests and code review rather than replacing them.
- Expect some false positives, and begin with the Recommended rules so the output stays manageable.
Exercise
A teammate says, "Our unit tests all pass with 90% coverage, so we don't need Code Analyzer." Give one concrete reason from this chapter why that reasoning is flawed. Then name one thing a clean Code Analyzer scan still cannot tell you.
Show answer
Tests only verify the inputs they use. A pattern such as a DML statement inside a loop passes a test with three records but exceeds the governor limit on a bulk load. Code Analyzer flags that pattern from the source alone. A clean scan still cannot show that the code's logic is correct or that it is free of every security flaw. It only means no enabled rule matched, and it never runs the code.
Exercise
A single scan reports violations from both PMD and ESLint. What shared field lets one CI threshold apply to both engines, and what are its possible values?
Show answer
The severity field. Code Analyzer maps every engine's findings onto one scale from 1 to 5: 1 Critical, 2 High, 3 Moderate, 4 Low, and 5 Info. A single threshold, such as 2, therefore applies to all engines.