What is a Trigger Handler pattern and what are its benefits?
Answer
The trigger contains no logic; it only routes events to a handler class with methods like beforeInsert, afterUpdate.
apex
trigger AccountTrigger on Account (before insert, after update) {
AccountTriggerHandler h = new AccountTriggerHandler();
switch on Trigger.operationType {
when BEFORE_INSERT { h.beforeInsert(Trigger.new); }
when AFTER_UPDATE { h.afterUpdate(Trigger.new, Trigger.oldMap); }
}
}
Benefits: reusable and unit-testable methods, clean separation of concerns, one place for recursion/bypass control, easier maintenance, and ability to use a base handler framework.
apex-triggertriggerhandlerbest-practices