Avoid Governor Limits

Salesforce is based on Multiteanet Architecture so they have imposed limits for the implementation of the Apex and customization of things. So the first and foremost challange in front of each developer is “Implementation of code avoiding governor limits”. So below are some tips and tricks to avoid governor limits
The governor limits are applied on the basis of the initiation of the code execution. The execution initiates from :-
  1. Apex Trigger
  2. Apex Web Service
  3. Anonymous Block
  4. Visualforce Controller
DML operations are basic needs of any implementation. so lets discuss the problem and the solution for this.
1.) Let’s have a look at the type of code that could cause this issue
public void functionName(List theNames){
for(String theName: theNames){
myObject__c obj = [SELECT processed__c FROM myObject__c WHERE name=:theName]; //This may result in ‘Too many SOQL queries’
obj.processed__c = true;
update obj; // Mistake #2 – may result in ‘Too many DML rows’
}
}
The SELECT statement will be run for each iteration of the loop i.e. a list of 200 names means 200 queries, which means 200 round trips, which means this isn’t going to work. The solution is to fetch all records for the object before the loop and then loop through the list of objects returned, thereby bypassing the need to query each time.
Solution :-
public void rhymeWithOrange(List theNames){
List objToUpdate = new List(); // intermediate list
List objects = [SELECT processed__c FROM myObject__c];
for(String myName: theNames){
for(myObject__c obj: objects){
if(theName==obj.name){
obj.processed__c = true;
objToUpdate.add(obj); // add processed objects to intermediate list
}
}
}
update objToUpdate; // update all objects at once to avoid SOQL execption
}
In above what we did is made a list of updated objects and then updated all in a single update statement just 1 statement.
There are other solution as well dependent on the situation which we will cover later such as Batchapex,Future Calls


Source : http://www.saasanalogy.com/avoid-governor-limits/

Comments

Popular posts from this blog

Salesforce.com: Expression Operators in Salesforce lightning Components

Custom Calendar on VisualForce Page

Salesforce.com: Scheduled Apex