Maximize your code quality with Salesforce Code Analyzer

Salesforce Code Analyzer is a command-line tool that unifies essential code scanners for Salesforce development.

Maximize your code quality with Salesforce Code Analyzer
Table of contents

These scanners are:

Not only does it help ISVs ensure the quality of their Salesforce packages and security reviews, but it also helps systems integrator companies when it comes to their Salesforce implementations.

You can only develop quality code if you are also reviewing it. Code reviews and, by extension, using tools like Salesforce Code Analyzer offer a boundless wellspring of ideas.

These ideas empower you to enhance the caliber of your company’s software, identifying and rectifying errors in their infancy during the developmental stage.

That’s why Salesforce Code Analyzer is your one-stop shop for writing and securing clean code.

The importance of clean code

📈
Having a healthy codebase is essential for the success of a Salesforce product or its implementation. 

The quality of the code implies several factors, such as:

  • The minimum number of bugs
  • Scalability
  • Robustness
  • Efficiency
  • Minimal technical debt.
Quality code ensures there isn't any vulnerability that can affect the product or leak any critical data.

You can follow rules like the ones below to write clean code in Salesforce:

  • Maintain short methods – in general, they should do just one thing
  • Pay attention to cyclomatic complexity findings
  • Avoid repetition
  • Have clear, intention-revealing names
  • Leave comments to clarify and make components better.

Ways to enhance code quality in Salesforce

Enhancing the quality of your Salesforce code can be achieved through several straightforward measures:

  • Adhere to coding standards and best practices – like having compact, understandable, and maintainable code
  • Craft neat code
  • Implement continuous integration practices
  • Conduct thorough manual code reviews.
🤯
It would, however, be a mighty task solely relying on manual methods of checking that every code convention complies with quality standards. 

That’s why automated code scanner tools – like Salesforce Code Analyzer – significantly streamline the process.

For example, if there weren't a code scanner for pull requests, Developers would need to manually check the defined rules for every file of a pull request. This would take up valuable time and effort.

The engines that power Salesforce Code Analyzer

Each of the engines that Salesforce Code Analyzer uses has a different purpose (although they may overlap in certain instances):

PMD

It is a static code analysis tool mainly used for Salesforce metadata, including Apex and any other XML metadata (such as Flows). It includes standard quality rules and allows for extension with custom rules.

ESLint

It's a static code analysis tool specifically designed for JavaScript codebases. It is beneficial for Lightning Web Components and Lightning Components.

RetireJS

It is a security-focused tool that scans JavaScript libraries for vulnerabilities. For example, it can scan Salesforce static resources for outdated JavaScript libraries.

Salesforce Graph Engine

It is the newest open-source scanner created by Salesforce and is used to detect quality issues. It uses a data flow analysis, which uncovers problems that other static code analysis tools may not pick up.

🔎
The combination of the four engines provides a complete perspective and report of the quality of an ISV’s Salesforce codebase. 

The format of the report can be configured by ISVs themselves.

ISVs need to use Salesforce Code Analyzer for the AppExchange

To further emphasize the importance of Salesforce Code Analyzer, it is required with certain AppExchange reviews.

Before you can publicly list your managed package on the AppExchange, it must pass a quality review. You must:

  • Scan your code with Salesforce Code Analyzer
  • Upload your scan reports to your submission in the AppExchange Security Review Wizard.
🔒
To access the AppExchange Security Review Wizard, log in to the Salesforce Partner Community. Click “Publishing,” go to “Technologies,” and “Solutions.” To open the wizard, click “Start Review” or “Edit Review.”

The limitations of Salesforce Code Analyzer

While Salesforce Code Analyzer performs a great job at picking up security and quality violations, it may not pick them all up.

For example, PMD works by patterns. It is thus possible that a security violation is introduced by a Developer using a pattern that PMD does not take into account.

🛠️
In this scenario, it is important that another Developer detects that violation during the code review phase. The same applies to quality rules and any other code analysis tool. 

The Code Analyzer is still a powerful, time-saving tool, which is why we, at Hutte, have created a recipe for it. Our recipe uses the analyzer to perform a quality scan of your metadata.

Hutte’s Salesforce Code Analyzer recipe

While Hutte helps with the management of orgs, deployments, packaging, and other aspects of the CI/CD lifecycle, Salesforce Code Analyzer is a complementary tool that adds value to the health of your codebase.

The main usage of this CLI is as a quality gate in the CI/CD process. It can be included in the pipeline of the Git provider (such as GitHub Actions, Bitbucket, etc.) to automatically analyze and assess the codebase during the CI/CD process.

By integrating this CLI tool into the pipeline, Developers can ensure that every code change or pull request goes through a rigorous code quality evaluation before being merged into the main branch or deployed to production.

🧑‍🍳
Let’s take a look at how to install and configure Hutte’s recipe. 

Prerequisites

  • A GitHub repository with a valid SFDX project.

Step 1

Each engine runs an independent job.

Therefore, you may exclude any of them if desired. Furthermore, the scans are configured to run in parallel, although they can be refactored to run sequentially either by joining them into the same job or using the “needs” property within them.

Create the following GitHub workflows and PMD ruleset:

  • .github/workflows/code-analyze.yml
# Based on https://github.com/mehdisfdc/sfdx-GitHub-actions/blob/main/.github/workflows/main.yml
name: Salesforce Code Quality

on:
  workflow_dispatch:
  workflow_call:

jobs:
  PMD:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
        with:
          fetch-depth: 0
      - uses: actions/setup-node@v3
      - name: Setup SFDX
        run: |
          npm install --global sfdx-cli
          sfdx --version
          sfdx plugins:install @salesforce/sfdx-scanner
      - name: SF Code Analyzer - PMD
        run: |
          sfdx scanner:run --engine pmd --target force-app --pmdconfig=pmd/ruleset.xml --format table --severity-threshold 3
      
  RetireJS:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
        with:
          fetch-depth: 0
      - uses: actions/setup-node@v3
      - name: Setup SFDX
        run: |
          npm install --global sfdx-cli
          sfdx --version
          sfdx plugins:install @salesforce/sfdx-scanner 
      - name: SF Code Analyzer - RetireJS
        run: |
          sfdx scanner:run --engine "retire-js" --target force-app --format table --severity-threshold 3 
      
  GraphEngine:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
        with:
          fetch-depth: 0
      - uses: actions/setup-node@v3
      - name: Setup SFDX
        run: |
          npm install --global sfdx-cli
          sfdx --version
          sfdx plugins:install @salesforce/sfdx-scanner 
      - name: SF Code Analyzer - Data Flow Analysis
        run: |
          sfdx scanner:run:dfa --target force-app --projectdir force-app --format table --severity-threshold 3

  ESLint:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
        with:
          fetch-depth: 0
      - uses: actions/setup-node@v3
      - name: Setup SFDX
        run: |
          npm install --global sfdx-cli
          sfdx --version
          sfdx plugins:install @salesforce/sfdx-scanner
      - name: SF Code Analyzer - ESLint
        run: |
          sfdx scanner:run --engine eslint --eslintconfig=.eslintrc.json --target "force-app/**/*.js" --format table --severity-threshold 3
  • .github/workflows/pr.yml
name: Pull Request

on:
  pull_request:

jobs:
  code-analyze:
    name: Run Salesforce Code Analyzer
    uses: ./.github/workflows/code-analyze.yml
    secrets: inherit
  • .github/workflows/main.yml
name: Main

on:
  push:
    branches:
      - main

jobs:
  code-analyze:
    name: Run Salesforce Code Analyzer
    uses: ./.github/workflows/code-analyze.yml
    secrets: inherit
  • pmd/ruleset.xml
<?xml version="1.0" ?>
<ruleset
    name="Baseline PMD Ruleset"
    xmlns="http://pmd.sourceforge.net/ruleset/2.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://pmd.sourceforge.net/ruleset/2.0.0 https://pmd.sourceforge.io/ruleset_2_0_0.xsd"
>
    <description>Baseline PMD Ruleset</description>

    <!-- DEFAULT RULE CATEGORIES -->
    <rule ref="category/apex/bestpractices.xml" />
    <rule ref="category/apex/codestyle.xml" />
    <rule ref="category/apex/design.xml" />
    <rule ref="category/apex/documentation.xml" />
    <rule ref="category/apex/errorprone.xml" />
    <rule ref="category/apex/performance.xml" />
    <rule ref="category/apex/security.xml" />
</ruleset>

Step 2

  • Create a pull request and verify the action was successfully run
  • Merge the pull request and check the action was executed.

You have the ingredients to brew a quality codebase

Salesforce Code Analyzer is adept at detecting intricate violations. This makes it an ideal tool for ISV and Salesforce Application Developers seeking to prepare for a thorough security review.

🚀
By employing Hutte’s Salesforce Code Analyzer recipe, teams can spot a wide range of quality and performance issues during the initial stages of development, leading to the delivery of superior solutions and products.
Hutte Recipes are available freely on GitHub and other popular Git hosts and right from within Hutte's UI.