Apex PMD is a static code analysis tool that identifies potential issues in our Salesforce Apex Code. It can highlight performance bottlenecks, security vulnerabilities, and maintainability concerns. Sometimes we need to suppress specific warnings if they are not relevant or if there is a justified reason. This post will help you suppress PMD warnings in Salesforce Apex.
Table of Contents
Key PMD Code Issues
Writing clean and efficient Apex code is crucial for maintaining a scalable and high-performing Salesforce application. However, even experienced developers can introduce issues that affect performance, security, or maintainability.
Below are a few important code quality issues flagged by PMD.
1. Code Quality Issues
This kind of warning can help you ensure best practices for maintainability and readability. Below are few important code quality issues
- AvoidDeeplyNestedIfStmts : Avoid writing deeply nested if-then statements because they are more difficult to read and error-prone to maintain.
- ExcessiveClassLength : This warning shows that the class is overburdened with a lot of responsibilities. It can be handled by external classes or functions.
- ExcessiveParameterList : This warning shows when we have multiple method parameters. We should avoid multiple parameters, as it will be difficult to maintain them in code. Multiple parameters also show that the method will be too much code, which is not good.
- ExcessivePublicCount: This warning shows when we have excessive public methods and properties. Large classes should be refactored into smaller, modular classes.
2. Best Practices Issues
These rules enforce generally accepted best practices.
- AvoidGlobalModifier : Global classes should be avoided (especially in managed packages) because they cannot be deleted or changed in signature. Check twice if something needs to be global.
- AvoidLogicInTrigger : Because triggers do not support methods like regular classes, they are less flexible and suited to good encapsulation style. Delegate the trigger work to a regular class.
- QueueableWithoutFinalizer : Detects when a Queueable interface is used but no Finalizer is attached. It is best practice to call the
System.attachFinalizer(Finalizer f)
method within theexecute
method of a class which implements theQueueable
interface
3. Security Issues
These rules flag potential security flaws in Salesforce Apex Code.
- ApexCRUDViolation : The rule ensures that you are checking for access permissions before performing a SOQL/SOSL/DML operation. Because Apex runs in system mode by default, failing to perform proper permissions checks leads to privilege escalation and may result in runtime errors.
- ApexSharingViolations : If DML methods are used, detect classes that have been declared without explicit sharing mode. This forces the developer to consider access restrictions before modifying objects.
- ApexSOQLInjection : This rule will detect the use of untrusted or unescaped variables in DML queries.
- ApexSuggestUsingNamedCred : It identifies hardcoded credentials used in requests to an endpoint.
There are other types of rules, like code styles, documentation, error-proneness, performance, etc., that should be adhered to.
Check out the post- Top 10 PMD Issues Salesforce Developers Should Focus on in Apex to learn about top PMD issues.
When Should You Suppress PMD Warnings?
Sometimes we need to suppress a few types of PMD warnings. Below are some conditions when we can suppress PMD warnings
1. False Positives
A false positive in PMD occurs when it flags a piece of Apex code as an issue, even though it follows best practices and is functionally correct. This happens due to:
- Generic rule implementation that doesn’t consider specific business logic.
- Edge cases that are valid but don’t conform to the predefined rules.
- Context-sensitive logic that PMD can’t analyse effectively.
Based on careful review, if a warning is false positive, it can be suppressed.
Example
PMD may flagSystem.debug()
but sometimes logging is necessary for troubleshooting.
public void processRecords() {
System.debug('Processing records...'); // PMD Warning 🚨
}
2. Performance Considerations
Sometimes, modifying code to comply with PMD rules might lead to performance degradation, especially when handling large data volumes or optimizing execution time. In such cases, suppressing the PMD rule is justified.
Before (Optimized for Performance)
public void processRecords(List<Account> accounts) {
for (Account acc : accounts) {
if (acc.Industry == 'Finance' || acc.Industry == 'Insurance') {
acc.Type = 'Financial';
}
}
}
After (More Readable but Slightly Slower)
public void processRecords(List<Account> accounts) {
for (Account acc : accounts) {
acc.Type = getIndustryType(acc.Industry); // Extra function call per iteration
}
}
private String getIndustryType(String industry) {
if (industry == 'Finance' || industry == 'Insurance') {
return 'Financial';
}
return 'General';
}
Justification for Supression
- Avoiding function calls inside loops improves CPU performance.
- Keeping logic inline prevents unnecessary method invocations in bulk operations.
3. Suppressing PMD for Business Requirements
Sometimes, business requirements force design choices that violate PMD rules. In such cases, suppression may be necessary to ensure the functionality aligns with business needs. However, it should be justified with proper comments and documentation.
Allowing SOQL in Loops for Small Data Set
Scenario: A business requirement states that only a small number of records (≤ 5) will ever be processed, making bulkification unnecessary.
for (String accName : accNames) {
// NOPMD: AvoidSOQLInLoops - Business case limits data size
Account acc = [SELECT Id FROM Account WHERE Name = :accName LIMIT 1];
processAccount(acc);
}
4. Suppressing PMD for Legacy Code Compatibility
When working with legacy Apex code, modifying it might not be feasible due to various reasons like dependencies, regression risks, or business constraints. In such cases, suppressing PMD warnings may be necessary.
Below scenario where suppressing PMD warnings makes sense:
Excessive Class or Method Length
Older classes or methods may be too long, but splitting them could cause unintended side effects. It will also required regression test that may be not feasible in most of situations.
@SuppressWarnings('PMD.ExcessiveClassLength')
public class LegacyBusinessLogic {
// Large amount of business logic
}
5. Third-Party Dependencies
When working with third-party libraries or integrations, certain coding styles may not align with Apex PMD rules. In such cases, you may need to suppress warnings to avoid unnecessary refactoring while maintaining compatibility.
Empty Catch Blocks in API Integration Code
Some APIs throw exceptions in some conditions, but it might be unusable for us. In this case, we can suppress an empty catch block.
try {
ExternalLibrary.callMethod();
} catch (Exception e) {
// NOPMD: External library expected to fail silently
}
How to suppress PMD warnings in Apex?
PMD warnings can be suppressed using annotations or comments.
1. Suppressing at the Class or Method Level
We can use @SuppressWarnings
annotation before a class or method to suppress PMD warnings in Apex.
In the below CustomerContoller class, the PMD warning to avoid the Global modifier is thrown; we can suppress it, if we need to use the Global modifier.
@SuppressWarnings('PMD.AvoidGlobalModifier')
global class CustomerContoller{
global void getCustomerById(string custId) {
System.debug('Hello');
}
}
2. Suppressing Inline using Comments
We can suppress specific method PMD warnings using comments as well. In the below example, we can avoid PMD warnings by simply putting inline suppression.
// NOPMD: AvoidGlobalModifier
global class CustomerContoller{
global void getCustomerById(string custId) {
System.debug('Hello'); // NOPMD: SystemDebug
}
}
Impact of Suppressing PMD Warnings
Suppressing PMD warnings in the Apex code can have both positive and negative impacts. While it helps in specific scenarios where rules may not be applicable, excessive suppression can lead to technical debt and reduce code quality.
1. Negative Impacts of Suppressing PMD Warnings
1.1 Hides Potential Security Risks:
Suppressing SOQL injection or hardcoded credentials related PMD rules can expose vulnerabilities in apex code.
1.2 Increases Technical Debt
Suppressing PMD warnings can increase technical debt. It can cause maintainability issues in the long run.
1.3 Reduces Code Quality & Performance
Suppressing best practice rules may result in inefficient code. It will degrade system performance.
2. Positive Impacts of Suppressing PMD Warnings
2.1 Reduces Unnecessary Refactoring
Some PMD warnings may not be relevant to the project’s context. Refactoring code will increase the project cost and time.
2.2 Improves Developer Productivity
Suppress warnings can increase developer productivity as they will avoid wasting time to fix minimal impact on performance or security.
2.3 Avoids False Positives
Some PMD rules may incorrectly flag valid codes. Suppressing such warnings prevents unnecessary modifications.
Best Practices for Suppressing PMD Warnings
✅ Suppress warnings only when necessary and justify them with comments.
✅ Regularly review suppressed warnings to ensure they are still valid.
✅ Use suppression at the smallest possible scope (e.g., method instead of class).
✅ Consider alternative solutions before suppressing warnings.
Summary
Suppressing PMD warnings is useful when necessary but should be done carefully. Overuse can lead to security risks, technical debt, and performance issues, so it’s important to strike a balance.
Related Posts
- How to Manage Technical Debt in Salesforce
- Optimizing Salesforce Apex Code
- DML or SOQL Inside Loops
- Limiting data rows for lists
- Disabling Debug Mode for production
- Stop Describing every time and use Caching of the described object
- Use Filter in SOQL
- Avoid Heap Size
- Optimize Trigger
- Bulkify Code
- Foreign Key Relationship in SOQL
- Defer Sharing Rules
- Avoid Hardcode in code
- Use Platform Caching