function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Raji MRaji M 

Can someone provide the ways to stop recursive in Triggers other than static variables.

Hi All,

Can someone tell me the different ways to stop recursive  triggers other than static variables approach. I had been using the static variables from day 1 of my coding but I heard that there are many different ways to stop it. I am not finding any articles about it. Can someone guide me in this.

Thanks in advance!

Thanks,
Raji M
Ajay K DubediAjay K Dubedi
Hi Raji,
Best practice for triggers to avoid Recursion:
 
1. One Trigger Per Object so that you don't have to think about the execution order as there is no control over which trigger would be executed first.
2. Logic-less Triggers - use Helper classes to handle logic.
3. Code coverage 100%
4. Handle recursion - To avoid the recursion on the trigger, make sure your trigger is getting executed only one time. You may encounter the error : 
'Maximum trigger depth exceeded' if recursion is not handled well. Here's an example of code using Static Set to avoid recursion. 
Class 
public class checkRecursive {
     public static Set<Id> SetOfIDs = new Set<Id>();
}
Trigger 
trigger TestTrigger on Account (before insert) {
    if (Trigger.isAfter && Trigger.isInsert) {
        List<Account> accList = new List<Account>();
      for (Account test: Trigger.new) {
          If(!checkRecursive.SetOfIDs.contains(test.Id)){
              test.Name = 'helloworld'; 
              accList.add(test);
            checkRecursive.SetOfIDs.add(test.Id);
          }
      }
      insert  accList;
    }
}


I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.
Thanks,
Ajay Dubedi