6 answers

Hi,Recursion occurs when the same code is executed again and again. It can lead to an infinite loop and which can result in governor limit sometime. Sometime it can also result in unexpected output.It is very common to have recursion in the trigger which can result in unexpected output or some error. So we should write code in such a way that it does not result to recursion. But sometimes we are left with no choice.For example, we may come across a situation wherein a trigger we update a field which in result invoke a workflow. The workflow contains one field update on the same object. So trigger will be executed two times. It can lead us to unexpected output.Another example is our trigger fires on after update, and it updates some related object, and there is one more trigger on a related object which updates child object. So it can result in too infinite loop.To avoid this kind of situation we can use a public class static variable.Use static variables to store information that is shared within the confines of the class. All instances of the same class share a single copy of the static variables. For example, all triggers that are spawned by the same request can communicate with each
other by viewing and updating static variables in a related class. A recursive trigger might use the value of a class variable to
determine when to exit the recursion.
In RecursiveTriggerHandler class, we have a static variable which is set to true by default.
In the following trigger, we are checking if the static variable is true only then trigger runs. Also, we are setting a static variable to false when trigger runs for the first time. So if the trigger will try to run a second time in the same request, then it will not run.public classRecursiveTriggerHandler{
private static boolean run = true;
public static boolean runOnce(){
if(run){
run=false;
return true;
}else{
return run;
}
}
}
Please check the below link for more details on Static variables .https://developer.salesforce.com/forums/?id=906F00000008un1IAAHope this helps you!Best Regards,Jyothsnatrigger SampleTrigger on Contact (after update){
Set<String> accIdSet = new Set<String>();
if(RecursiveTriggerHandler.isFirstTime){
RecursiveTriggerHandler.isFirstTime = false;
for(Contact conObj : Trigger.New){
if(conObj.name != 'SFDC'){
accIdSet.add(conObj.accountId);
}
}
// Use accIdSet in some way
}
}