This post is part of the series – Design Pattern in Apex
Today in this post I will explain how Singleton Design Pattern can be used to stop calling the same trigger twice.
Consider the situation – You as a developer, is updating a field in Trigger which in turns calls a workflow and in that workflow action you are again updating some other field from the same object. And to your surprise, the same trigger is getting triggered again. Getting confused, right?
Let’s become more specific with the situation.
Consider the below object – Airport__c
The requirements are –
- Req 1: Send an email if the country and type of an airport changed.
- Req 2: If the country of an airport changed to “India”, change the type to “International”.
- One trigger, which will send the email if the country and type of an airport changed.
- One workflow, which will change the type to “International” (Workflow action) if the country of an airport changed to “India”.
MyAirportTrigger –
With the above approach, as you can see we are checking for boolean value in the trigger(line# 4 & 10). If the value is false, then only we are sending the loop and at the same time changing the value to true. So the next time, in the same transaction, even if the trigger is getting called, it will not do any operation, because we have changed the boolean value to true.
I hope you have understood how singleton design pattern can be used to stop calling same trigger recursively. Please let me know your feedback. Thanks.