Hello friends, Here we will learn What is Trigger Factory in Salesforce and How to implement it? Trigger Factory is a pattern that avoids multiple bad practices such as multiple triggers on an object and Repetitive SOQL queries that can exceed governer limit.

What is Trigger Factory in Salesforce and How to implement it?

Trigger Factory is a pattern that avoids bad practices such as:

  • Repetitive SOQL queries that can exceed governer limit.
  • Multiple triggers over the same object.

Keeping trigger logic for each object in a single place avoids such problems where multiple triggers are in contention with each other and make it easier to debug. Enforcing upfront caching of data within a trigger keeps the trigger bulkified and avoids those nasty ‘too many SOQL queries’.

This pattern involves delegating work from the trigger to a structured Trigger Handler class. Each object will have its own trigger handler. The trigger itself has almost no code in it. We make use of a Factory class to instantiate the appropriate Trigger Handler. Whenever we create a new trigger all we need to do is create a new Handler Class, add a few lines of code to the Factory class to register the correct handler and add a line of code to the trigger itself to delegate the work.

We start by defining an Interface that provides the template for our trigger handlers. This interface contains the methods and signatures that each handler must implement.

This example will take Opportunity as an example object

Implement Trigger Factory Pattern in Salesforce:

ITrigger interface:

Create TriggerException  Class:

Exception Handling Class:

Create OpportunityHandler class:

Now I will add a Opportunity handler class that implements the interface ITrigger. This class will contains some logic for any object on which you are creating Trigger.

Create TriggerFactory Class:

This class is responsible for selecting the correct handler for the target object. This is done by passing the object type to the static method CreateHandler

Create Trigger on Opportunity Object:

Now we are done with the Trigger Factory pattern

View More:

Conclusion:

I hope you will love this post. Your feedback and suggestions are appreciated. Please don’t hesitate to comment for any technical help.

Thank You.

Leave a Comment