Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 36 ยท Triggers

The Trigger Handler Pattern

Organise Apex trigger logic with the handler pattern: a logic-free trigger, a handler class with before and after methods, a base class, recursion control, with stand-ins.

Trigger code that grows inside the .trigger file quickly becomes unreadable and untestable. By the time a trigger handles validation, defaults, roll-ups and notifications, hundreds of lines pile up in one place, with nothing to reuse. The trigger handler pattern fixes this: the trigger file contains almost nothing, and the real logic lives in a normal Apex class.

The real classes below are read-only because they need an org. The Java stand-ins model the dispatching so you can run and change them.

Why separate the logic?

  • Testable: a class with methods can be called from a test, without saving records through the trigger.
  • Readable: each event has its own method; each method does one job.
  • Controlled order: one trigger per object means you decide the sequence of steps.
  • Reusable: other code (a batch job, an API) can call the same logic.

The logic-free trigger

Java
trigger AccountTrigger on Account (before insert, before update, after insert, after update) {
    new AccountTriggerHandler().run();
}

Every event hits one line. Nothing else is in the file.

A base class

You can write the dispatching once and reuse it for every object:

Java
public virtual class TriggerHandler {

    public void run() {
        if (!Trigger.isExecuting) { return; }
        switch on Trigger.operationType {
            when BEFORE_INSERT { beforeInsert(Trigger.new); }
            when BEFORE_UPDATE { beforeUpdate(Trigger.new, Trigger.oldMap); }
            when BEFORE_DELETE { beforeDelete(Trigger.old); }
            when AFTER_INSERT  { afterInsert(Trigger.new); }
            when AFTER_UPDATE  { afterUpdate(Trigger.new, Trigger.oldMap); }
            when AFTER_DELETE  { afterDelete(Trigger.old); }
            when AFTER_UNDELETE { afterUndelete(Trigger.new); }
        }
    }

    // empty defaults: subclasses override only what they need
    protected virtual void beforeInsert(List<SObject> newRecords) {}
    protected virtual void beforeUpdate(List<SObject> newRecords, Map<Id, SObject> oldMap) {}
    protected virtual void beforeDelete(List<SObject> oldRecords) {}
    protected virtual void afterInsert(List<SObject> newRecords) {}
    protected virtual void afterUpdate(List<SObject> newRecords, Map<Id, SObject> oldMap) {}
    protected virtual void afterDelete(List<SObject> oldRecords) {}
    protected virtual void afterUndelete(List<SObject> newRecords) {}
}

virtual means a subclass may override the method. Trigger.operationType is an enum, so the switch is exhaustive and readable.

A concrete handler

Java
public class AccountTriggerHandler extends TriggerHandler {

    protected override void beforeInsert(List<SObject> newRecords) {
        AccountDefaults.apply((List<Account>) newRecords);
    }

    protected override void beforeUpdate(List<SObject> newRecords, Map<Id, SObject> oldMap) {
        AccountValidator.checkIndustryChange((List<Account>) newRecords, (Map<Id, Account>) oldMap);
    }

    protected override void afterInsert(List<SObject> newRecords) {
        WelcomeTaskService.createFor((List<Account>) newRecords);
    }
}

The handler is a thin coordinator. The real work sits in small, focused classes (AccountDefaults, AccountValidator, WelcomeTaskService), each of which can be tested alone. The casts (List<Account>) newRecords convert the generic list to a typed one.

flowchart TD
    T["AccountTrigger<br/>(one line)"] --> H["AccountTriggerHandler.run()"]
    H --> B["beforeInsert"]
    H --> U["beforeUpdate"]
    H --> A["afterInsert"]
    B --> S1["AccountDefaults"]
    U --> S2["AccountValidator"]
    A --> S3["WelcomeTaskService"]

The trigger only dispatches. Services hold the rules.

A runnable model of the pattern

This Java model has a base TriggerHandler with run, an AccountTriggerHandler that overrides only the events it cares about, and a tiny "platform" that calls run for different operations.

Java Stand-in (Java): base handler and an Account handler

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Recursion control in the base class

Handlers can include a guard so each record Id is processed once per operation. The idea in a short Java model:

Java Stand-in (Java): recursion guard with a set of processed Ids

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Bypassing triggers

Data migrations and tests sometimes need to skip the trigger logic. A common design adds a custom setting or custom metadata flag, or a static bypass set, which the base class checks:

Java
public static Set<String> bypassed = new Set<String>();
public static void bypass(String handlerName) { bypassed.add(handlerName); }

Use bypasses sparingly and always document them: a skipped trigger means skipped business rules.

Frameworks

Teams often adopt an open-source trigger framework or write their own tiny base class as shown above. The key ideas remain the same: one trigger per object, no logic in the trigger file, one method per event, shared helpers for recursion and bypass.

Common mistakes

  • Putting SOQL/DML in the trigger file and calling it a handler.
  • Forgetting the cast from List<SObject> to a typed list.
  • Giving a handler method too many unrelated jobs.
  • Creating several handlers for the same object that each run on the same event with no defined order.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What should the .trigger file contain in the handler pattern?

    The trigger dispatches to a handler class. Logic lives in classes that are easy to test and reuse.
  2. 2. What does the virtual keyword allow?

    A virtual method has a default implementation that subclasses may override.
  3. 3. Why is Trigger.operationType useful in the base class?

    Switching on the enum dispatches each event to its own method.
  4. 4. Why is a Set<Id> guard better than a single Boolean?

    A Boolean would block later batches of the same transaction; a Set<Id> blocks only repeated records.

Summary

  • Keep triggers logic-free: one trigger per object that calls a handler.
  • A base handler dispatches on Trigger.operationType to overridable methods.
  • Concrete handlers coordinate small service classes that are easy to test.
  • Add recursion control and an optional bypass mechanism in the base class.

Next: Apex Classes, Interfaces and Access Modifiers