Skip to content
Tutorials Center
My learning

Topics

Lesson 34 of 36 ยท Projects and Practice

Project: A Trigger Handler Framework

Build a reusable Apex trigger handler framework: a base class, one trigger per object, recursion guard, bypass switch and tests, with a runnable Java dispatcher you can extend.

Triggers are easy to start and painful to maintain. Without structure you end up with several triggers on one object, logic mixed into the trigger file, no control over order, recursion bugs and tests that are hard to write. In this project you build a small trigger handler framework in Apex: one trigger per object, a base class that routes each event to an overridable method, a recursion guard and a bypass switch. It brings together classes and inheritance, test classes and test data.

Apex cannot run on this site. The Apex listings are the real design, read-only. The Java section at the end is a runnable stand-in of the dispatcher so you can try the routing, the recursion guard and the bypass flag.

Goals

  1. Exactly one trigger per object, containing no logic.
  2. A base class with one method per event (beforeInsert, afterUpdate and so on).
  3. Handlers work on lists (bulk-safe by design).
  4. A way to turn a handler off for data loads or tests.
  5. Protection against infinite recursion.

Step 1: the base class

APEX
public virtual class TriggerHandler {

    private static Set<String> bypassed = new Set<String>();
    private static Map<String, Integer> runCounts = new Map<String, Integer>();

    public static void bypass(String handlerName) { bypassed.add(handlerName); }
    public static void clearBypass(String handlerName) { bypassed.remove(handlerName); }

    protected Integer maxLoops = 5;

    public void run() {
        String name = String.valueOf(this).substring(0, String.valueOf(this).indexOf(':'));
        if (bypassed.contains(name) || !Trigger.isExecuting) {
            return;
        }
        Integer count = runCounts.containsKey(name) ? runCounts.get(name) : 0;
        runCounts.put(name, ++count);
        if (count > maxLoops) {
            throw new TriggerHandlerException('Maximum loop count of ' + maxLoops + ' reached in ' + name);
        }

        switch on Trigger.operationType {
            when BEFORE_INSERT { beforeInsert(); }
            when BEFORE_UPDATE { beforeUpdate(); }
            when BEFORE_DELETE { beforeDelete(); }
            when AFTER_INSERT  { afterInsert(); }
            when AFTER_UPDATE  { afterUpdate(); }
            when AFTER_DELETE  { afterDelete(); }
            when AFTER_UNDELETE { afterUndelete(); }
        }
    }

    protected virtual void beforeInsert() { }
    protected virtual void beforeUpdate() { }
    protected virtual void beforeDelete() { }
    protected virtual void afterInsert() { }
    protected virtual void afterUpdate() { }
    protected virtual void afterDelete() { }
    protected virtual void afterUndelete() { }

    public class TriggerHandlerException extends Exception { }
}

Trigger.operationType returns a System.TriggerOperation enum, so a switch on statement reads cleanly. Static variables live for one transaction, which is exactly the scope a recursion counter needs.

Step 2: the trigger

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

Nothing else goes in the trigger file.

Step 3: a handler

APEX
public with sharing class AccountTriggerHandler extends TriggerHandler {

    private List<Account> newAccounts;
    private Map<Id, Account> oldMap;

    public AccountTriggerHandler() {
        this.newAccounts = (List<Account>) Trigger.new;
        this.oldMap = (Map<Id, Account>) Trigger.oldMap;
    }

    protected override void beforeInsert() {
        setDefaultRating(newAccounts);
    }

    protected override void afterUpdate() {
        List<Id> renamed = new List<Id>();
        for (Account a : newAccounts) {
            if (a.Name != oldMap.get(a.Id).Name) {
                renamed.add(a.Id);
            }
        }
        if (!renamed.isEmpty()) {
            System.enqueueJob(new RenameSyncJob(renamed));
        }
    }

    private void setDefaultRating(List<Account> accounts) {
        for (Account a : accounts) {
            if (a.Rating == null) {
                a.Rating = 'Warm';
            }
        }
    }
}

Observe the habits: loop over the whole list, compare old and new to act only on real changes, never query or run DML inside the loop, and hand follow-up work to a queueable in one call.

Step 4: tests

APEX
@isTest
private class AccountTriggerHandlerTest {

    @isTest
    static void defaultsRatingInBulk() {
        List<Account> accounts = TestDataFactory.createAccounts(200, false);
        Test.startTest();
        insert accounts;
        Test.stopTest();

        Assert.areEqual(200, [SELECT COUNT() FROM Account WHERE Rating = 'Warm']);
    }

    @isTest
    static void bypassSkipsTheHandler() {
        TriggerHandler.bypass('AccountTriggerHandler');
        insert TestDataFactory.createAccounts(5, false);
        TriggerHandler.clearBypass('AccountTriggerHandler');

        Assert.areEqual(0, [SELECT COUNT() FROM Account WHERE Rating = 'Warm']);
    }
}

Design choices to discuss

  • Why one trigger per object? Salesforce does not guarantee the order of several triggers on the same object and event, so logic in them can conflict.
  • Why a bypass? Data migrations and some tests need to skip heavy logic. Keep bypass for code, and use a custom permission or custom setting for an admin-controlled switch.
  • Should handlers be with sharing? Usually yes. Put the keyword on the concrete handler, as above.
  • Flows vs triggers: use Flow for simple declarative automation; keep Apex for complex or high-volume logic. Mixing both on one object needs care about order of execution.

Try the idea: the dispatcher (Java stand-in)

The Java version below is a stand-in that models the dispatcher: operation routing, a loop counter and a bypass.

Java Stand-in: trigger dispatcher with recursion guard and bypass (Java)

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.

The counter starts at the first normal insert, so the update loop trips the limit sooner than five runs; that is the guard doing its job. In real Apex the counters reset at the end of the transaction.

Extend it

  • Add Contact and Opportunity handlers and triggers.
  • Skip work in afterUpdate when nothing relevant changed (compare old and new).
  • Add a custom metadata type that lists handlers to disable, and read it in run.
  • Add a logging hook that records handler runtime.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why should an object have only one trigger?

    Order is undefined across multiple triggers, so keep one trigger that calls an ordered handler.
  2. 2. What belongs inside the trigger file in this framework?

    The trigger is a thin entry point; logic lives in the handler class.
  3. 3. Why is a static counter suitable for a recursion guard?

    Statics are scoped to one transaction, which is exactly how long a trigger loop can happen.
  4. 4. What is the main habit that keeps a handler bulk-safe?

    Handlers receive up to 200 records; process them as a list with queries and DML outside the loops.

Summary

  • One trigger per object delegates to a handler; the base class routes events and guards recursion.
  • Handlers work on whole lists, compare old and new values and delegate follow-up work asynchronously.
  • A bypass switch helps data loads and tests.
  • Test in bulk, test the bypass, and keep Flows in mind.

Next: Project: A Nightly Data Cleanup Pipeline