Close Menu
SalesforceCodex
    Facebook X (Twitter) Instagram
    Trending
    • How to Build a Generic Modal Window in Lightning Web Component
    • Top 10 Salesforce Flow Features of Salesforce Summer ’25
    • Unlock the Power of Vibe Coding in Salesforce
    • How to Implement Dynamic Queueable Chaining in Salesforce Apex
    • How to Implement Basic Queueable Chaining in Salesforce Apex
    • How to Suppress PMD Warnings in Salesforce Apex
    • Top 10 PMD Issues Salesforce Developers Should Focus on in Apex
    • How to Use Graph API for Outlook-Salesforce Connection
    Facebook X (Twitter) Instagram
    SalesforceCodex
    Subscribe
    Thursday, May 29
    • Home
    • Architecture
    • Salesforce
      • News
      • Apex
      • Integration
      • Books Testimonial
    • Questions
    • Certification
      • How to Prepare for Salesforce Integration Architect Exam
      • Certification Coupons
    • Integration Posts
    • Downloads
    • About Us
      • Privacy Policy
    SalesforceCodex
    Home»Salesforce»How to Suppress PMD Warnings in Salesforce Apex

    How to Suppress PMD Warnings in Salesforce Apex

    Dhanik Lal SahniBy Dhanik Lal SahniMarch 23, 2025No Comments8 Mins Read
    Facebook Twitter Pinterest LinkedIn Tumblr Email
    Suppress PMD Warnings
    Share
    Facebook Twitter LinkedIn Pinterest Email

    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
      • When Should You Suppress PMD Warnings?
      • 1. False Positives
        • How to suppress PMD warnings in Apex?
          • Impact of Suppressing PMD Warnings
            • Best Practices for Suppressing PMD Warnings
            • Summary
            • Related Posts

            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 the execute method of a class which implements the Queueable 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
            apex apex code analysis apex code best practice apex performance apex pmd best code practice code analysis code quality Code Scanning. codescan pmd salesforce salesforce apex Salesforce PMD
            Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
            Previous ArticleTop 10 PMD Issues Salesforce Developers Should Focus on in Apex
            Next Article How to Implement Basic Queueable Chaining in Salesforce Apex
            Dhanik Lal Sahni
            • Website
            • Facebook
            • X (Twitter)

            With over 18 years of experience in web-based application development, I specialize in Salesforce technology and its ecosystem. My journey has equipped me with expertise in a diverse range of technologies including .NET, .NET Core, MS Dynamics CRM, Azure, Oracle, and SQL Server. I am dedicated to staying at the forefront of technological advancements and continuously researching new developments in the Salesforce realm. My focus remains on leveraging technology to create innovative solutions that drive business success.

            Related Posts

            By Dhanik Lal Sahni4 Mins Read

            How to Build a Generic Modal Window in Lightning Web Component

            May 26, 2025
            By Dhanik Lal Sahni6 Mins Read

            Top 10 Salesforce Flow Features of Salesforce Summer ’25

            May 11, 2025
            By Dhanik Lal Sahni6 Mins Read

            Unlock the Power of Vibe Coding in Salesforce

            April 30, 2025
            Add A Comment
            Leave A Reply Cancel Reply

            Ranked #1 SALESFORCE DEVELOPER BLOG BY SALESFORCEBEN.COM
            Featured on Top Salesforce Developer Blog By ApexHours
            Recent Posts
            • How to Build a Generic Modal Window in Lightning Web Component
            • Top 10 Salesforce Flow Features of Salesforce Summer ’25
            • Unlock the Power of Vibe Coding in Salesforce
            • How to Implement Dynamic Queueable Chaining in Salesforce Apex
            • How to Implement Basic Queueable Chaining in Salesforce Apex
            Ranked in Top Salesforce Blog by feedspot.com
            RSS Recent Stories
            • How to Connect Excel to Salesforce to Manage Your Data and Metadata February 9, 2025
            • Difference Between With Security and Without Security in Apex January 2, 2025
            • Top Reasons to Love Salesforce Trailhead: A Comprehensive Guide December 5, 2024
            • How to Utilize Apex Properties in Salesforce November 3, 2024
            • How to Choose Between SOQL and SOSL Queries July 31, 2024
            Archives
            Categories
            Tags
            apex (111) apex code best practice (8) apex rest (11) apex trigger best practices (4) architecture (22) Asynchronous apex (9) AWS (5) batch apex (9) batch processing (4) code optimization (8) code review tools (3) custom metadata types (5) design principle (9) file upload (3) flow (15) future method (4) google (6) google api (4) integration (19) integration architecture (6) lighting (8) lightning (64) lightning-combobox (5) lightning-datatable (10) lightning component (30) Lightning web component (62) lwc (51) named credential (8) news (4) optimize apex code (4) Permission set (4) pmd (3) Queueable (9) rest api (23) S3 Server (4) salesforce (141) salesforce apex (46) salesforce api (4) salesforce api integration (5) Salesforce Interview Question (4) salesforce news (5) salesforce question (5) solid (6) tooling api (5) Winter 20 (8)

            Get our newsletter

            Want the latest from our blog straight to your inbox? Chucks us your detail and get mail when new post is published.
            * indicates required

            Ranked #1 SALESFORCE DEVELOPER BLOG BY SALESFORCEBEN.COM
            Featured on Top Salesforce Developer Blog By ApexHours
            Recent Posts
            • How to Build a Generic Modal Window in Lightning Web Component
            • Top 10 Salesforce Flow Features of Salesforce Summer ’25
            • Unlock the Power of Vibe Coding in Salesforce
            • How to Implement Dynamic Queueable Chaining in Salesforce Apex
            • How to Implement Basic Queueable Chaining in Salesforce Apex
            Ranked in Top Salesforce Blog by feedspot.com
            RSS Recent Stories
            • How to Connect Excel to Salesforce to Manage Your Data and Metadata February 9, 2025
            • Difference Between With Security and Without Security in Apex January 2, 2025
            • Top Reasons to Love Salesforce Trailhead: A Comprehensive Guide December 5, 2024
            • How to Utilize Apex Properties in Salesforce November 3, 2024
            • How to Choose Between SOQL and SOSL Queries July 31, 2024
            Archives
            Categories
            Tags
            apex (111) apex code best practice (8) apex rest (11) apex trigger best practices (4) architecture (22) Asynchronous apex (9) AWS (5) batch apex (9) batch processing (4) code optimization (8) code review tools (3) custom metadata types (5) design principle (9) file upload (3) flow (15) future method (4) google (6) google api (4) integration (19) integration architecture (6) lighting (8) lightning (64) lightning-combobox (5) lightning-datatable (10) lightning component (30) Lightning web component (62) lwc (51) named credential (8) news (4) optimize apex code (4) Permission set (4) pmd (3) Queueable (9) rest api (23) S3 Server (4) salesforce (141) salesforce apex (46) salesforce api (4) salesforce api integration (5) Salesforce Interview Question (4) salesforce news (5) salesforce question (5) solid (6) tooling api (5) Winter 20 (8)

            Get our newsletter

            Want the latest from our blog straight to your inbox? Chucks us your detail and get mail when new post is published.
            * indicates required

            Facebook X (Twitter) Instagram Pinterest YouTube Tumblr LinkedIn Reddit Telegram
            © 2025 SalesforceCodex.com. Designed by Vagmine Cloud Solution.

            Type above and press Enter to search. Press Esc to cancel.

            Ad Blocker Enabled!
            Ad Blocker Enabled!
            Our website is made possible by displaying online advertisements to our visitors. Please support us by disabling your Ad Blocker.