Recursion is the process when a trigger calls itself repeatedly and leads to an infinite loop. There may be a chance to hit the governor limit with Recursive Triggers. We always wanted to avoid Recursive Triggers but many Apex Triggers, Process Builder, Record-Triggered Flow, and Work Flow are there on Single Object with parent-child updates then we can easily face the recursive trigger issue.
So today I will share a few methods using which we can easily avoid recursive triggers. Let's go in deep:
How to avoid recursion in triggers?
There are different ways to solve the recursion in the trigger. We will go through each way one by one:
1. Use Static Boolean Variable
We can use the Static boolean variable to avoid recursion. Initially set this boolean variable to true and once execution is completed set it to false. In the trigger, before executing your code keep a check that the variable is true or not. Once you check make the variable false.
Apex Class
Apex Trigger
Static in Salesforce is per transaction, so the value will be true only for the current transaction. This practice is good for less than 200 records. It will update the first 200+ records then it will skip. PLEASE DON'T USE IT.
2. Use Static Set or Map
Instead of using Boolean Variable, we can use Set or Map to store all executed record ids. So, when next time it will execute again, we can check record Id is already executed or not. Let's see how we can use it:
2.1 Use Static Set
Let's try the above code for more than 200 records and see the result. The use of Set is not perfect because it is possible that you may get both insert and update within the same transaction.
2.2 Use Static Map
By using Map, you can handle all events using the same map.
3. Follow Best Practices for Triggers
Follow best practices and trigger frameworks to avoid recursion.
- One Trigger per Object so you don't have to think about the execution order as there is no control over which trigger would be executed first.
- Logic-less Triggers - use a helper class to handle logic
- Code coverage 100%
- Handle recursion - To avoid the recursion on a 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.
Comments