Saturday, 25 October 2014

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, to avoid 50001 limit error.

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

Exception will be thrown, if there are more than 50000 records.

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

    // Your logic here

    update acct;
}

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 datasets 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 hardcode SFDC record ids.

No comments:

Post a Comment