Best Practices of Apex In Salesforce

Share This Post

Please follow these Salesforce Best Practices to improve our code Quality, Readability, and Reusability. Also, you can use Salesforce Best Practices to optimize our code.

  1. Avoid DML/SOQL/SOSL statements in loops : 
  • Do not place SOQL or DML(insert/update/delete/undelete) statements inside a loop
  • When these operations are placed inside a for loop, database operations are invoked once per iteration of the loop making it very easy to reach these SFDC governor limits.
  • Solution: Move SOQL/DML out of loops
  • Query: If you need query results, get all the records using a single query and iterate over the resultset
  • Update: If you need to update, batch up the data into a collection and invoke DML once for that collection
  1. Bulkify your Code
  2. Using Collections, Streamlining Queries, and Efficient For Loops
  3. Querying Large Data Sets
  4. Use of the Limits Apex Methods to Avoid Hitting Governor Limits
  5. Use @future Appropriately
  6. Writing Test Methods to Verify Large Datasets
  7. Avoid Hardcoding IDs : 
  • Make sure that the helper methods are properly designed to handle bulk records
  • These methods should be written to be invoked with a set of records, especially if the technique has a SOQL query or DML operation
  • Use the power of the SOQL where clause to query all data needed in a single query
public static void hardCodeIdExample() { 
        if (opp.RecordTypeId == '016500000005WAr') {
            //do some logic here.....
        } else if (opp.RecordTypeId == '016500000008WAr') {
            //do some logic here for a different record type...
        }
   }

If you run the above code in different environments, it will fail. Then Please use this code snippet:

public static void hardCodeIdExample() {
        if (opp.RecordTypeId ==           Schema.sObjectType.Opportunity.getRecordTypeInfosByName().get('Test') ) {
            //do some logic here.....
        } else if (opp.RecordTypeId == Schema.sObjectType.Opportunity.getRecordTypeInfosByName().get('TestData’')) {
            //do some logic here for a different record type...
        }
}
  1. Bulkify your Helper Method :
  • Make sure that the helper methods are correctly designed to handle bulk records
  • These methods should be written to be invoked with a set of records, especially if the technique has a SOQL query or DML operation
  • Use the power of the SOQL where clause to query all data needed in a single query
  1. Use only one trigger per SObject Type. 
  2. Avoid logic in the trigger
  3. Apex unit test should not use SeeAllData True
  4. Naming conventions : 
  • Apex Class naming convention (Pascal case)

E.g. :  public class DataClass { }

  • Method naming conventions (Camel  Case)

E.g. : public void testMethod() { }

  • Field or local variable naming conventions (Camel Case)

E.g. : Integer instanceField;

For More Salesforce Naming Conventions refer to this link: Salesforce Naming Conventions

  1. Apex unit test class should have asserts
  • One Assert Statement per method: Always include asserting statements for positive and negative tests.
  • System.assert(condition, msg)
  • System.assertEquals(expected, actual, msg)
  • System.assertNotEquals(expected, actual, msg)
  1. Increase readability by indenting code and breaking up long lines.
  2. Avoid nesting loops within loops.
  3. Write comments with a good balance between quality and quantity (explain, but don’t over-explain). Always provide documentation comments (method and class headers). Provide inline comments only when necessary to clarify complex code.
  4. Break methods into multiple smaller methods if possible, making your code more modular and easier to read and maintain.
  5. Make reusability of Apex Code
  6. Code coverage
    • Bulk Records
    • Positive & Negative testing.
    • Restricted User testing.
    • One Assert Statement per method
    • should not use @isTest(seeAllData=true)
  7. Use Database Methods while doing DML operation
  8. Test Multiple Scenarios

Note: If you are using Visual Studio Code as your IDE, consider using the Apex PMD extension (included in the Resources section) to automatically check your code for best practices.

Conclusion

I hope you like this blog and if you want any help let me know in the comment section.

Stay tuned, there is way more to come! Follow me on LinkedIn, Instagram, and Twitter. So you won’t miss out on all future articles.

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe To Our Newsletter

Get updates and learn from the best

More To Explore

NetSuite Salesforce Integration: An Automation Guide

NetSuite Salesforce Integration is the seamless connection between NetSuite, a leading cloud-based Enterprise Resource Planning (ERP) system, and Salesforce, a premier Customer Relationship Management (CRM) platform.