Trigger Handler Pattern in Salesforce

What is a Trigger Handler Pattern in Salesforce?

The Trigger Handler Pattern is a design pattern in Salesforce used to organize and manage trigger logic in a clean, reusable, and scalable way. Instead of writing logic directly in the trigger, you delegate that logic to an Apex class.

Why Use Trigger Handler Pattern?

  • Separates logic from the trigger
  • Makes code easier to test and maintain
  • Supports bulk operations and avoids governor limit issues
  • Prepares your org for future enhancements

Traditional Trigger (Not Recommended)

trigger ContactTrigger on Contact (before insert) {
  for(Contact con : Trigger.new) {
    if(con.Email == null) {
      con.Email = 'sfdctelugu@gmail.com';
    }
  }
}

This logic works, but it’s hard to scale, test, or reuse.

Using Trigger Handler Pattern (Recommended)

Step 1: Create a Trigger

trigger ContactTrigger on Contact (before insert) {
  ContactTriggerHandler.handleBeforeInsert(Trigger.new);
}

Step 2: Create a Handler Class

public class ContactTriggerHandler {
  public static void handleBeforeInsert(List<Contact> newList) {
    for(Contact con : newList) {
      if(con.Email == null) {
        con.Email = 'sfdctelugu@gmail.com';
      }
    }
  }
}

This approach keeps your trigger clean and moves the logic to a separate, testable class.

Conclusion

Using the trigger handler pattern improves code quality and keeps your Salesforce org organized. It’s a best practice followed in professional development projects, and every serious developer should follow it!

Leave a Comment

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

Scroll to Top