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”. 
To achieve the above two requirements, we have implemented –
  • 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”.
Here is the trigger –

The trigger looks really simple. But you know what will happen, when you will change the country of an airport to “India”, you will get two emails. You know why?

First email you will get from Line#6
After that, workflow action will change the type of the airport to “International”. Due to this change you will get another email from Line#11.

To solve this we need to implement Singleton Design Patten as shown below –
StopRecursive – 


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.