“Bulkify Your Code” – Another Example with Use Case
This post is the continuation of my previous post”Bulkify Your Code” – Explanation of Salesforce’ Governor Limit with Use CaseUse Case -I have two custom objects (Airport__c and Country__c). Below screenshot will give you field details.My requirement is to make sure when I am inserting an Airport record, I need to check whether the country mentioned in the record is already present in the Country object, if not, then create a new Country record with name same as mentioned in the Airport’s Country field provided that Aiport is operational i.e. Operational__c == true.Solution -Initially it may look like the requirement is very easy to implement. But we need to keep in mind the Salesforce’s Governor Limit.If we go ahead with the approach of iterating over each new Airport record and then do a query against Country object to check whether that country is already there in the system, we will quickly hit Salesforce’s Governor Limit – “Total number of SOQL Issued – 100 (Synchronized) and 200 (Asynchronized)”.So we need to make sure that our code is efficient. Below is the optimized trigger which can handle the requirement and at the same time will make sure that we will not hit by Governor limit.trigger AirportTrigger on Airport__c (after insert) { List<Country__c> allCountries = new List<Country__c>(); List<String> allCountryNames = new List<String>(); //Fetch all Country Name and put it into a list...
Read More