Trigger Handler Pattern

A trigger handler pattern separates trigger entry points from the business logic. This improves maintainability and helps you keep logic testable.

Typical trigger body


trigger LeadTrigger on Lead (before insert, before update, after update) {
    LeadTriggerHandler.handle(Trigger.new, Trigger.oldMap, Trigger.operationType);
}
  

Handler structure

The handler class decides what to do based on the context and keeps the trigger page clean.


public class LeadTriggerHandler {
    public static void handle(List newList, Map oldMap, System.TriggerOperation operation) {
        if (Trigger.isBefore) {
            if (Trigger.isInsert) {
                beforeInsert(newList);
            } else if (Trigger.isUpdate) {
                beforeUpdate(newList, oldMap);
            }
        }

        if (Trigger.isAfter && Trigger.isUpdate) {
            afterUpdate(newList, oldMap);
        }
    }

    private static void beforeInsert(List leads) {
        // validation or defaulting logic
    }

    private static void beforeUpdate(List leads, Map oldMap) {
        // detect changes and prevent bad updates
    }

    private static void afterUpdate(List leads, Map oldMap) {
        // perform related updates or notifications
    }
}
  

Why this helps

Tip

Keep the handler class focused on trigger behavior. Move unrelated business rules into service classes when possible.

← Back to Apex