Salesforce Apex Best Practices #EP-01 : Bulkify Your Apex Code

Bulkification of your code is the process of making your code able to handle multiple records at a time efficiently.

Bulkification is achieved by breaking up your queries into chunks.

Take a look at the code below – it shows an example of code that hasn’t been written with bulkification in mind.

trigger OpportunityTrigger on Opportunity(before insert)
{
    if (Trigger.isInsert){
        // Insert Opportunity
        Opportunity opp = Trigger.new[0];
        if(opp.Amount > 10000){  
            // Call Apex helper for further processing
            Opportunityhelper.applyOwnerRecord(opp);
        }
    }
}

Below is the same code set up to handle the full batch of records in the trigger, meaning all 200 records would be correctly processed in a single trigger invocation.

trigger OpportunityTrigger on Opportunity(before insert)
{
    if (Trigger.isInsert){
        if (Trigger.isBefore) {
        // Insert Opportunity
       for(Opportunity opp = Trigger.new){
         if(opp.Amount > 10000){
                // Call Apex helper for further processing
                Opportunityhelper.applyOwnerRecord(opp);
            }
       }
     // Process after insert
        }   
    }
}

// Helper class for trigger

public class Opportunityhelper {
    public static void applyOwnerRecord(List<Opportunity> Opplist) {
        Set<Id> accountIds = new Set<Id>();

               for(Opportunity opp : Opplist){

        accountIds.add(opp.Account.Id);

        }

              Map<Id,Account> accountById = new Map<Id,Account>(            [SELECT Id,Name FROM Account WHERE Id IN: accountIds]

        );

        for(Opportunity opp : Opplist){

            opp.Account.Name = accountById.get(opp.Account.Id).Name;

        }

    }
}

//Consider use of maps can greatly reduce the complexity and the amount of time it takes your code to run by reducing the overall lines of code to be executed when compared to iterating over lists.

Did you find this article valuable?

Support Tarun Gupta by becoming a sponsor. Any amount is appreciated!