Let’s start from the beginning. No, not from the Big Bang, but from static code analysis. Every developer needs it to inspect possible issues without executing a program. If we are talking about static code analysis in Salesforce, there are tools like PMD with a set of rules to check Apex and Visualforce code.
In this article, I will tell you about my favorite tool, Salesforce Code Analyzer, and why you should try it right now (examples included).
What Is Code Analyzer?
Salesforce Code Analyzer is an open-source SFDX plugin whose purpose is to help developers write clean and secure code. This tool takes in the power of different static analyzers and puts it all together. As a result, you get one solution with all the needed functionality.
Code Analyzer supports multiple engines:
- PMD – for checking Apex and Visualforce code,
- Eslint, Eslint-LWC and Eslint-Typescript – for JS-based files,
- RetireJS – for searching vulnerabilities in external libraries that you are using,
- CPD – copy-paste detector (for those who like to just copy a piece of code and forget about refactoring 🙂),
- Salesforce Graph Engine – a powerful tool that uses data flow analysis to detect Create, Read, Update, and Delete and Field-Level Security (CRUD/FLS) violations.
Why Do You Need Code Analyzer?
As Salesforce developers, we must follow high coding standards to deliver secure and neat code. So it is handy to have this all-in-one plugin to handle all code in one place. Moreover, Salesforce recommends using Code Analyzer throughout the development cycle of the AppExchange apps to save time and nerves during the security review.
How Code Analyzer Can Enhance Your Code
Let’s check some examples. I will use a demo project provided by Salesforce, but with slight changes for easier violation’s track. Then we will try to fix found issues with the help of Code Analyzer. Follow this simple instruction to install the tool.
Our Apex class:
public with sharing class AuraEnabledFls {
public final static String ACCOUNT = 'Account';
public final static String CONTACT = 'Contact';
public final static String FIRST_NAME = 'FirstName';
public final static String LAST_NAME = 'LastName';
public final static String Phone = 'Phone';
@AuraEnabled
public static Account flsHelperInsertAccount() {
FlsHelperClass accountHelper = new FlsHelperClass(ACCOUNT);
FlsHelperClass contactHelper = new FlsHelperClass(CONTACT);
String[] fieldsToCheck = new String[]{FIRST_NAME, phone};
if (fieldToChecks != null) {
if (fieldToChecks.size() > 0) {
if (accountHelper != null) {
for (String fieldToCheck : fieldsToCheck) {
accountHelper.verifyCreateable(fieldToCheck);
Account a = new Account(
FirstName = 'Enway',
LastName = 'Journal',
Phone = '312-555-0123'
);
insert a;
}
}
} else {
// TODO: add ELSE actions
}
}
return a;
}
}
We will run a Code Analyzer tool with the command:
sfdx scanner:run --target './force-app/main/default/classes/AuraEnabledFls.cls' --projectdir './force-app/main/default' --outfile scan.html
Let’s open the file with results:
open scan.html
We have got a report in HTML format with all problems we need to fix:
There are Documentation, Code Style, Design, Performance, Error Prone, Best Practices and Security issues – seems like a Full house! Let’s fix the code:
/**
* @description This class contains method for inserting account with CRUD and FLS validations
*/
public with sharing class AuraEnabledFls {
public final static String ACCOUNT = 'Account';
public final static String CONTACT = 'Contact';
public final static String FIRST_NAME = 'FirstName';
public final static String LAST_NAME = 'LastName';
public final static String PHONE = 'Phone';
/*******************************************************************************
* @description method for inserting and returning account
* @return Account
******************************************************************************/
@AuraEnabled
public static Account flsHelperInsertAccount() {
FlsHelperClass accountHelper = new FlsHelperClass(ACCOUNT);
String[] fieldsToCheck = new String[]{FIRST_NAME, PHONE};
for (String fieldToCheck : fieldsToCheck) {
accountHelper.verifyCreateable(fieldToCheck);
}
Account a = new Account(FirstName = 'Enway', LastName = 'Journal', Phone = '312-555-0123');
insert a;
return a;
}
}
Now we have a pretty Apex class but still with one Security issue. But why the Code Analyzer doesn’t understand the verifyCreateable method from FlsHelterClass, which actually checks CRUD validation?
Code Analyzer wants to see something like this:
if (!Schema.sObjectType.Account.fields.Name.isCreateable() &&
!Schema.sObjectType.Account.fields.Phone.isCreateable()) {
throw new PermissionsException();
}
We don’t have to do it because now we can check CRUD/FLS with the help of Salesforce Graph Engine in Code Analyzer. This tool uses data flow analysis that kind of emulates code execution. Let’s try it:
sfdx scanner:run:dfa --target './force-app/main/default/classes/AuraEnabledFls.cls' --projectdir './force-app/main/default' --outfile scanDfa.html
We will check results once again:
Woah, another error! This time Graph Engine has shown us exactly what is wrong with our CRUD validations – we forgot to check if LastName is insertable. Let’s fix it.
String[] fieldsToCheck = new String[]{FIRST_NAME, LAST_NAME, PHONE};
Finally, that’s it! No errors or violations are found.
Tip: if there are no violations, the report won’t be created.
Conclusion
Salesforce Code Analyzer is really helpful when it comes to code inspection. I hope my example has cast a light on the tool’s features. I recommend Code Analyzer to every Salesforce developer, especially if you are developing AppExchange applications.