Avoid recursive trigger in salesforce using static variable

Avoid recursive trigger in salesforce using static variable

Avoid recursive trigger in salesforce using static variable
Recursion occurs when same code is executed again and again. It can lead to infinite loop and which can result to governor limit sometime. Sometime it can also result in unexpected output.
It is very common to have recursion in trigger which can result to unexpected output or some error. So we should write code in such a way that it does not result to recursion. But sometime we are left with no choice.
For example, we may come across a situation where in a trigger we update a field which in result invoke a workflow. Workflow contains one field update on 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 related object which updates child object. So it can result too infinite loop.
To avoid these kind of situation we can use public class static variable.
In RecursiveTriggerHandler class, we have a static variable which is set to true by default.
public class RecursiveTriggerHandler{

public static Boolean isFirstTime = true;

In following trigger, we are checking if static variable is true only then trigger runs. Also we are setting static variable to false when trigger runs for first time. So if trigger will try to run second time in same request then it will not run.
trigger SampleTrigger on Contact (after update){

 Set<String> accIdSet = new Set<String>();
       RecursiveTriggerHandler.isFirstTime = false;
          for(Contact conObj : Trigger.New){
              if(conObj.name != 'SFDC'){
        // Use accIdSet in some way

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s