Salesforce triggers are a powerful tool for automating business logic, but poor implementation can lead to inefficiencies, recursion issues, and governor limits. In this blog post, we’ll explore advanced trigger design patterns to ensure your triggers are scalable, efficient, and easy to maintain.
A well-structured trigger follows best practices to prevent issues like:
Implementing Trigger Handler Patterns can help maintain a clean and optimized approach to Salesforce automation.
Having multiple triggers on the same object can lead to execution order unpredictability. Instead, use a single trigger per object and delegate logic to a handler class.
trigger AccountTrigger on Account (before insert, before update, after insert, after update) {AccountTriggerHandler.handleTrigger(Trigger.new, Trigger.oldMap, Trigger.operationType);}
By calling a separate handler class, we maintain cleaner, more structured code.
Apex Trigger Frameworks like TriggerHandler help you scale automation by centralizing logic.
public abstract class BaseTriggerHandler {public virtual void beforeInsert(List<SObject> newRecords) {}public virtual void beforeUpdate(List<SObject> newRecords, Map<Id, SObject> oldRecords) {}}
If a trigger modifies records that cause another trigger to fire, an infinite loop may occur.
public class TriggerHelper {private static Boolean isTriggerRunning = false;public static Boolean shouldRun() {if (isTriggerRunning) return false;isTriggerRunning = true;return true;}}
This ensures your trigger only runs once per transaction, preventing unintended recursion.
Hardcoded SOQL queries inside loops are a common mistake in trigger development.
for (Account acc : Trigger.new) {Contact c = [SELECT Id FROM Contact WHERE AccountId = :acc.Id LIMIT 1];}
Map<Id, Account> accounts = new Map<Id, Account>([SELECT Id, Name FROM Account WHERE Id IN :Trigger.newMap.keySet()]);
This approach retrieves all necessary records in a single SOQL query, preventing governor limit exceptions.
By implementing these advanced Apex trigger design patterns, you can ensure your Salesforce triggers remain efficient, scalable, and maintainable. Whether you’re handling complex business logic or automating workflows, following these best practices will future-proof your org’s automation.
Would you like to learn more about a specific trigger framework? Let us know in the comments!
Quick Links
Legal Stuff