Architecture
Trigger Framework
One trigger per object. All logic delegated to handler classes. No business logic in .trigger files.
AccountTrigger.trigger
Apex
// Thin trigger — context routing only trigger AccountTrigger on Account ( before insert, before update, before delete, after insert, after update, after delete, after undelete ) { AccountTriggerHandler handler = new AccountTriggerHandler(); if (Trigger.isBefore) { if (Trigger.isInsert) handler.onBeforeInsert(Trigger.new); if (Trigger.isUpdate) handler.onBeforeUpdate(Trigger.new, Trigger.oldMap); if (Trigger.isDelete) handler.onBeforeDelete(Trigger.old); } else { if (Trigger.isInsert) handler.onAfterInsert(Trigger.new); if (Trigger.isUpdate) handler.onAfterUpdate(Trigger.new, Trigger.oldMap); if (Trigger.isDelete) handler.onAfterDelete(Trigger.old); if (Trigger.isUndelete) handler.onAfterUndelete(Trigger.new); } }
AccountTriggerHandler.cls
Apex
public class AccountTriggerHandler { // before insert: set defaults, validation, field population public void onBeforeInsert(List<Account> newAccounts) { AccountService.setDefaultRating(newAccounts); AccountValidator.validateRequiredFields(newAccounts); } // before update: detect changes using oldMap public void onBeforeUpdate(List<Account> newAccounts, Map<Id, Account> oldMap) { List<Account> changed = new List<Account>(); for (Account acc : newAccounts) { Account old = oldMap.get(acc.Id); if (acc.BillingState != old.BillingState) { changed.add(acc); } } if (!changed.isEmpty()) { AccountService.recalculateTax(changed); } } // after insert: async operations, platform events, notifications public void onAfterInsert(List<Account> newAccounts) { AccountService.enrichAccounts(newAccounts); PlatformEventService.publishAccountCreated(newAccounts); } public void onBeforeDelete(List<Account> oldAccounts) {} public void onAfterUpdate(List<Account> newAccs, Map<Id, Account> oldMap) {} public void onAfterDelete(List<Account> oldAccounts) {} public void onAfterUndelete(List<Account> newAccounts) {} }