Trigger handler pattern in Salesforce

The trigger handler pattern is a design pattern used in Salesforce development to manage and organize Apex triggers. The Salesforce Trigger Handler Framework is a lightweight apex trigger framework. The Trigger Handler pattern is a best practice for managing Apex triggers in the Salesforce platform. This pattern helps ensure the trigger code is well-organized, efficient, and maintainable.

What is the Trigger Handler pattern in Salesforce?

The basic idea behind the Trigger Handler pattern is to separate the trigger logic into a separate class from the trigger itself. The trigger class is responsible for registering the trigger with the appropriate events (such as before insert or after update), and for delegating the actual logic to the handler class.

Trigger Handler Pattern

Learn about Salesforce Apex Best practices.

How to implement Trigger Handler pattern.

1. One Trigger Per Object

A single Apex Trigger is all you need for one particular object. If you develop multiple Triggers for a single object, you have no way of controlling the order of execution if those Triggers can run in the same contexts.

trigger AccountTrigger on Account( after insert, after update, before insert, before update) {
    AccountTriggerHandler handler = new AccountTriggerHandler(Trigger.isExecuting, Trigger.size);
    
    if( Trigger.isInsert ){
        if(Trigger.isBefore) {
            handler.OnBeforeInsert(trigger.New);
        }
        else {
            handler.OnAfterInsert(trigger.New);
        }
    }
    else if ( Trigger.isUpdate ) {
        if(Trigger.isBefore){
            handler.OnBeforeUpdate(trigger.New ,trigger.Old,Trigger.NewMap,Trigger.OldMap);
        }
        else{
            handler.OnAfterUpdate(trigger.New ,trigger.Old,Trigger.NewMap,Trigger.OldMap);
        }
    }
}

If you write methods in your Triggers, those can’t be exposed for test purposes. You also can’t expose logic to be re-used anywhere else in your org.

2. Trigger Handler Class

Create context-specific handler methods in Trigger handlers. The handler class is where the actual logic of the trigger is implemented. It should be designed to handle multiple trigger events and sObjects, and should be flexible enough to allow for easy modification and extension.

public with sharing class AccountTriggerHandler 
{
    private boolean m_isExecuting = false;
    private integer BatchSize = 0;
    public static boolean IsFromBachJob ;
    public static boolean isFromUploadAPI=false;
    
    public AccountTriggerHandler(boolean isExecuting, integer size)
    {
        m_isExecuting = isExecuting;
        BatchSize = size;
    }
            

    public void OnBeforeInsert(List<Account> newAccount)
    {
        system.debug('Account Trigger On Before Insert');
    }
    public void OnAfterInsert(List<Account> newAccount)
    {
        system.debug('Account Trigger On After Insert');
    }
    public void OnAfterUpdate( List<Account> newAccount, List<Account> oldAccount, Map<ID, Account> newAccountMap , Map<ID, Account> oldAccountMap )
    {
        system.debug('Account Trigger On After Update ');
        AccountActions.updateContact (newAccount);
    }
    public void OnBeforeUpdate( List<Account> newAccount, List<Account> oldAccount, Map<ID, Account> newAccountMap , Map<ID, Account> oldAccountMap )
    {
        system.debug('Account Trigger On Before Update ');
    }

    @future 
    public static void OnAfterUpdateAsync(Set<ID> newAccountIDs)
    {

    }      
    public boolean IsTriggerContext
    {
        get{ return m_isExecuting;}
    }
    
    public boolean IsVisualforcePageContext
    {
        get{ return !IsTriggerContext;}
    }
    
    public boolean IsWebServiceContext
    {
        get{ return !IsTriggerContext;}
    }
    
    public boolean IsExecuteAnonymousContext
    {
        get{ return !IsTriggerContext;}
    }
} 

3. Trigger Helper Class

The helper class stores the business logic, which can be reused for other services.

public with sharing class AccountActions 
{
    public static void updateContact ( List<Account> newAccount)
    {
        // Add your logic here
    }
}

Advantage of Trigger Handler pattern

Let’s talk about the advantages of the Trigger Handler pattern.

  1. Apex Class that handles trigger logic
  2. Allows code to be called from other code or tests
  3. Uses specific Trigger contexts and Trigger variables for routing
  4. Keep Triggers Simple
  5. Allow for greater flexibility
  6. Make code reusable
  7. Unit tests are much easier

Limitation of Trigger Handler pattern

What is missing in the Handler pattern?

  1. Still duplicated code in every trigger
  2. How can we simplify things?
  3. How can we make our process repeatable?

What next?

Check out different Apex Trigger Frameworks.

What is the Trigger handler pattern in Salesforce?

The Trigger Handler pattern separates the trigger logic into a separate class from the trigger itself. The trigger class is responsible for registering the trigger with the appropriate events and delegating the logic to the handler class.

Trigger Handler Pattern Video

YouTube video

Summary

Using the Trigger Handler pattern, developers can ensure their trigger code is modular, reusable, and easy to maintain. This can lead to more efficient and effective development, increased productivity, and reduced technical debt.

Leave a Reply

Your email address will not be published. Required fields are marked *