"One Trigger Per Object" Pattern

The "One Trigger per Object" pattern is a best practice in Salesforce development that involves consolidating multiple trigger logic into a single, well-structured trigger handler class per object. This pattern helps to maintain clean and organized code, reduces the risk of trigger order issues, and facilitates better code reuse and maintainability.

Trigger Handler Class

public class AccountTriggerHandler {
    
    public static void onBeforeInsert(List<Account> newList) {
        // Your before insert logic here
    }
    
    public static void onBeforeUpdate(List<Account> newList, Map<Id, Account> oldMap) {
        // Your before update logic here
    }
    
    public static void onBeforeDelete(List<Account> oldList) {
        // Your before delete logic here
    }
    
    // Add methods for after insert, after update, after delete, and any other trigger events as needed
    
    // Example method for handling custom logic
    public static void customLogic(List<Account> newList, Map<Id, Account> oldMap) {
        // Your custom logic here
    }

}

Trigger Calls the Trigger Method

trigger AccountTrigger on Account (before insert, before update, before delete) {
    
    // Call the appropriate handler methods based on trigger event
    if (Trigger.isBefore) {
        if (Trigger.isInsert) {
            AccountTriggerHandler.onBeforeInsert(Trigger.new);
        } else if (Trigger.isUpdate) {
            AccountTriggerHandler.onBeforeUpdate(Trigger.new, Trigger.oldMap);
        } else if (Trigger.isDelete) {
            AccountTriggerHandler.onBeforeDelete(Trigger.old);
        }
    }
    
    // Optionally, you can call additional handler methods for after events
}

Benefits of this Pattern:

Modularity: Each trigger handler class focuses on specific object-related logic, making the code easier to understand and maintain.
Reduced Complexity: Consolidating logic into a single handler class reduces the complexity of individual triggers, making them easier to manage and debug.
Avoids Trigger Order Issues: By consolidating logic, you can ensure that the order of execution is consistent across different trigger events.
Code Reusability: Handler methods can be reused across different trigger events and even across different triggers for the same object.

Comments

Popular posts from this blog

Introduction to Salesforce Agent Script: Build Predictable AI Agents

Anti-Patterns in Salesforce Agentforce: What to Avoid When Building AI Agents

MCP vs. Traditional APIs: Choosing the Right Integration Approach