Monday, October 28, 2019

APEX TRIGGER BEST PRACTICES SALESFORCE


Here are the best practices that we should follow while designing triggers.

1) BULKIFY YOUR CODE.

Here is an example of a poorly written code that handles only one record at a time.

trigger singleRecordTriggere on Account(before insert) {
    Account obj = Trigger.New[0]; // Trigger handling a single record
    obj.industry = 'Agriculture';
}

Here is an example of code written to handle bulkification,

trigger contactTrigger on contact (before insert, before update) {
 List<Contact> conList =new List<Contact>();
    for(contact con:trigger.new){
        if(con.firstName="Testing"){
               con.dummyContact__c=true;
                conList.add(con);
            }
   }
}

2) Avoid SOQL Queries or DML statements inside FOR Loops as discussed above.

3) SINGLE TRIGGER PER OBJECT.

If we have multiple triggers on one object we cannot control the order of execution. To avoid multiple triggers on an object, we can make use "Trigger Handler Framework Salesforce" as described in below
article.

No comments:

Post a Comment