Triggers – Best Practices in Salesforce

Triggers – Best Practices in Salesforce

1. Future methods, SOQL and DML:
Avoid writing Future methods, SOQL and DML inside the “For” loop.

2. Bulkify the trigger:
Start developing the logic for bulk of records getting inserted or updated or deleted. Trigger will be invoked when we insert bulk of records from any data loading tools or through Web services. So, we should not concentrate on 1 record, we have to concentrate on bulk of records.

3. Larger sets of records:
Use SOQL in For loop for larger set of records.

Account[] accts = [SELECT id FROM account];

for ( Account acc : accts ) {

    // Your logic here
 
}

Instead of above SOQL, use the below

for ( List<Account> acct : [SELECT id, name FROM account WHERE name LIKE ‘Test’] ) {

    // Your logic here

}

The Force.com platform chunk your large query results into batches of 200 records by using this syntax where the SOQL query is in the for loop definition, and then handle the individual data-sets in the for loop logic.

4. Make use of the Limits Apex Methods to check whether we are nearing Governor Limits.
Number of SOQL Queries allowed in this Apex code context – Limits.getLimitQueries()
Number of records that can be queried  in this Apex code context – Limits.getLimitDmlRows()
Number of DML statements allowed in this Apex code context – Limits.getLimitDmlStatements()
Number of CPU usage time (in ms) allowed in this Apex code context – Limits.getLimitCpuTime()

5. Never hard-code record ids.

Leave a Reply