Apex Best Practices & Context Variables

Trigger Context Variables

IsInsert " IsUpdate " IsDelete " IsUndelete
isBefore isAfter isBefore isAfter isBefore isAfter isAfter
new Available Available Available Available Available
old Available Available Available Available
newMap Available Available Available Available
oldMap Available Available Available Available

Apex Best Practices

  1. Bulkify Your Code
    • Bulkifying Apex means making sure that it properly handles more than one record at a time
  2. Avoid SOQL Queries or DML Statements inside FOR Loops
    • This can trips governor limits that enforce a maximum number of SOQL queries/DML statements
  3. Bulkify Your Helper Methods
  4. Use Collections, Streamline Queries, and Write Efficient For Loops
    • Use Apex Collections to efficiently query data and store it in memory. Thoughtfully combining appropriate collections with streamlined SOQL queries will help write efficient Apex code and avoid hitting governor limits.
  5. Use a Single Trigger per Object
    • Salesforce is not able to enforce the order of execution for multiple triggers, so best practice is to collapse multiple triggers developed independently into a single trigger
  6. Querying Large Data Sets
    • SOQL queries can only return 50,000 records at a time. If you are hitting heap limits, use a SOQL for loop to batch process records.
  7. Use the Limits Apex Methods to Avoid Hitting Governor Limits
    • The Limits class lets you output debug messages for each governor limit, which can help triage particularly resource-intensive Apex.
  8. Use @future Appropriately
    • Asynchronous methods have an independent set of higher governor limits, but it still has governor limits. And, no more than 10 @future methods can be invoked within a single Apex transaction.
  9. Write Test Methods to Verify Large Datasets
    • An Apex trigger can be invoked by either a data operation from the user interface (generally single records) or by a data operation from an API (often many records). Use test methods that verify that all Apex code is properly designed to handle larger datasets without exceeding governor limits.
  10. Avoid Hardcoding IDs
    • Record IDs can change between sandbox and production, so use logic and code that can dynamically identify the proper data to operate against without failing.

Use Cases for Asynchronous Apex

  • Future Methods:
    • Callouts to external Web services
    • Operations which can run in their own thread
    • To prevent the mixed DML error
  • Batch Apex:
    • When processing is required on many records
    • Jobs that need larger query results
  • Queueable Apex:
    • Processing on non-primitive data types
    • Chaining of jobs
    • To start a long-running operation and get an ID for it
  • Scheduled Apex:
    • When a process needs to be run at some specific time