is live. Lifetime & Yearly plans on offer. thankful for you ๐Ÿงก

Get the Black Friday deal

Blog

Apex Trigger Handler Pattern: A Step-by-Step Example

How the Apex trigger handler pattern works: a one-line trigger, a handler class routed by context, a static recursion guard and unit tests you can copy.

By Teja, ex-Salesforce engineer ยท Updated November 24, 2026 ยท 8 min read

Apex Trigger Handler Pattern: A Step-by-Step Example

The Apex trigger handler pattern keeps each trigger down to one line that hands control to a handler class. The handler decides which method runs for each context (before insert, after update and so on), and that method holds the business logic. You end up with one trigger per object, logic you can unit test without firing DML, and one place to add recursion guards and bypass switches.

Below is a complete, deployable example on the Account object: the trigger, a small base class, a concrete handler, a recursion guard, and the test class.

Why logic belongs in a handler class

A trigger body is a poor home for business logic. You can't call it directly from a test, and you can't reuse it. Once it holds more than a few if (Trigger.isBefore && Trigger.isInsert) blocks, it gets hard to follow. Moving the logic out fixes three problems.

Easier testing. Logic in the trigger body only runs when you perform DML. Logic in a handler method that accepts List<Account> and Map<Id, Account> can be called with records you build in memory, and you can assert on them without touching the database. Tests run faster and failures point straight at the method that broke.

One trigger per object. Salesforce does not guarantee the order in which multiple triggers on the same object run for the same event. If you have AccountTrigger1 and AccountTrigger2, both on before update, you can't rely on which fires first. With one trigger per object and a handler, the order is whatever your handler code says it is.

Clear context routing. Every context has different data available. In before insert, records have no Ids yet. In after triggers, Trigger.new is read-only. A handler with one method per context makes those rules obvious, and the routing code sits in one place instead of being copied into every trigger.

ConcernLogic in the trigger bodyTrigger handler pattern
Unit testingOnly through DMLCall methods directly with in-memory records
Execution orderNot guaranteed across multiple triggersControlled in one handler
Context checksRepeated isBefore/isInsert blocksOne switch in a base class
Recursion controlAd hoc, per triggerOne static guard per handler
Turning logic off for data loadsEdit and redeploy the triggerFlip a bypass flag

What each trigger context gives you

Each context gives the handler different data. That's why the base class below passes different arguments to different methods.

ContextTrigger.newTrigger.old / oldMapnewMapCan edit Trigger.new fields without DML
before insertYesNoNo (no Ids yet)Yes
after insertYesNoYesNo (read-only)
before updateYesYesYesYes
after updateYesYesYesNo (read-only)
before deleteNoYesNoNot applicable
after deleteNoYesNoNot applicable
after undeleteYesNoYesNo (read-only)

To see what Trigger.new actually holds in each context, read What's the content of Trigger.new?.

The requirements for our example

We'll build three rules on Account:

  1. Before insert: if Rating is blank, default it to Warm.
  2. Before update: once Industry has a value, users can't clear it.
  3. After update: when Rating changes to Hot, create a follow-up Task for the account owner.

Rule 3 is the one that can misfire through recursion. We'll deal with that in Step 4.

Step 1: The trigger (one line)

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

Register every event, even ones you don't use yet. Adding a context later then only means overriding a method in the handler. You won't need to edit and redeploy the trigger.

Step 2: A small base class that routes by context

Trigger.operationType returns a System.TriggerOperation enum value such as BEFORE_INSERT or AFTER_UPDATE. A switch on it replaces the nested Boolean checks.

public virtual class TriggerHandler {

    public static Set<String> bypassedHandlers = new Set<String>();
    private final String handlerName;

    public TriggerHandler(String handlerName) {
        this.handlerName = handlerName;
    }

    public void run() {
        if (!Trigger.isExecuting || bypassedHandlers.contains(handlerName)) {
            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, Trigger.oldMap); }
            when AFTER_INSERT   { afterInsert(Trigger.new, Trigger.newMap); }
            when AFTER_UPDATE   { afterUpdate(Trigger.new, Trigger.oldMap); }
            when AFTER_DELETE   { afterDelete(Trigger.old, Trigger.oldMap); }
            when AFTER_UNDELETE { afterUndelete(Trigger.new, Trigger.newMap); }
        }
    }

    protected virtual void beforeInsert(List<SObject> newList) {}
    protected virtual void beforeUpdate(List<SObject> newList, Map<Id, SObject> oldMap) {}
    protected virtual void beforeDelete(List<SObject> oldList, Map<Id, SObject> oldMap) {}
    protected virtual void afterInsert(List<SObject> newList, Map<Id, SObject> newMap) {}
    protected virtual void afterUpdate(List<SObject> newList, Map<Id, SObject> oldMap) {}
    protected virtual void afterDelete(List<SObject> oldList, Map<Id, SObject> oldMap) {}
    protected virtual void afterUndelete(List<SObject> newList, Map<Id, SObject> newMap) {}
}

You write this class once and every object's handler extends it. The empty virtual methods mean a handler only overrides the contexts it cares about. The bypassedHandlers set lets a test, a data migration script or an Apex job switch off a specific handler for the rest of the transaction.

Step 3: The Account handler

public with sharing class AccountTriggerHandler extends TriggerHandler {

    private static Set<Id> hotFollowUpIds = new Set<Id>();

    public AccountTriggerHandler() {
        super('AccountTriggerHandler');
    }

    protected override void beforeInsert(List<SObject> newList) {
        setDefaultRating((List<Account>) newList);
    }

    protected override void beforeUpdate(List<SObject> newList, Map<Id, SObject> oldMap) {
        preventIndustryClear((List<Account>) newList, (Map<Id, Account>) oldMap);
    }

    protected override void afterUpdate(List<SObject> newList, Map<Id, SObject> oldMap) {
        createHotFollowUps((List<Account>) newList, (Map<Id, Account>) oldMap);
    }

    @TestVisible
    private static void setDefaultRating(List<Account> accounts) {
        for (Account acc : accounts) {
            if (String.isBlank(acc.Rating)) {
                acc.Rating = 'Warm';
            }
        }
    }

    @TestVisible
    private static void preventIndustryClear(List<Account> accounts, Map<Id, Account> oldMap) {
        for (Account acc : accounts) {
            Account oldAcc = oldMap.get(acc.Id);
            if (String.isNotBlank(oldAcc.Industry) && String.isBlank(acc.Industry)) {
                acc.addError('Industry cannot be cleared once it has been set.');
            }
        }
    }

    @TestVisible
    private static void createHotFollowUps(List<Account> accounts, Map<Id, Account> oldMap) {
        List<Task> tasks = new List<Task>();
        for (Account acc : accounts) {
            Boolean becameHot = acc.Rating == 'Hot' && oldMap.get(acc.Id).Rating != 'Hot';
            if (becameHot && !hotFollowUpIds.contains(acc.Id)) {
                hotFollowUpIds.add(acc.Id);
                tasks.add(new Task(
                    WhatId = acc.Id,
                    OwnerId = acc.OwnerId,
                    Subject = 'Follow up: account marked Hot',
                    ActivityDate = Date.today().addDays(2)
                ));
            }
        }
        if (!tasks.isEmpty()) {
            insert tasks;
        }
    }
}

Notes on the design:

  • The override methods do nothing except cast and delegate. The logic lives in @TestVisible static methods that take typed lists and maps, which is what makes them testable without a trigger.
  • The casts are safe because inside an Account trigger, Trigger.new is a List<Account> at runtime.
  • createHotFollowUps collects Tasks in a list and runs one insert at the end. Putting DML or SOQL inside the loop is the most common way triggers hit governor limits. For a fuller treatment, see Apex Bulkification: Fix 'Too Many SOQL Queries: 101'.
  • Before-context rules (default values, validation) edit Trigger.new directly and need no DML. After-context rules work on related records.

Step 4: Stop recursion with a static flag

Static variables in Apex live for the whole transaction, so they can remember that a piece of logic already ran. You need that memory here because an update trigger can fire more than once in one save.

The common case: a workflow field update or a record-triggered flow updates the same Account after your trigger runs, and the update triggers fire again. With a workflow field update there's a twist. On the re-fire, Trigger.old holds the record as it was before the original update, not the intermediate version. So oldMap.get(acc.Id).Rating != 'Hot' is still true on the second pass, and without a guard you'd create two Tasks.

The simple Boolean flag, and why it breaks

The first version most developers write looks like this:

public class AccountTriggerState {
    public static Boolean afterUpdateRan = false;
}

// inside afterUpdate
if (AccountTriggerState.afterUpdateRan) {
    return;
}
AccountTriggerState.afterUpdateRan = true;
createHotFollowUps(...);

It works for single-record saves from the UI. It fails on bulk operations. Triggers process records in chunks of 200, so updating 250 Accounts fires the trigger twice in the same transaction: once for records 1 to 200, then once for 201 to 250. The Boolean is already true when the second chunk arrives, so those 50 records never get their Task, and nothing raises an error.

The Set of Ids version (used in the handler above)

Tracking which records have been processed fixes the chunking problem:

private static Set<Id> hotFollowUpIds = new Set<Id>();
// ...
if (becameHot && !hotFollowUpIds.contains(acc.Id)) {
    hotFollowUpIds.add(acc.Id);
    // build the Task
}

The second chunk contains different Ids, so it's processed normally. A re-fire on the same records is skipped. One trade-off to know about: if a single transaction legitimately moves a record from Hot to Warm and back to Hot, the guard suppresses the second Task. For a follow-up Task that's usually the behaviour you want. For other logic, you might key the set on Id plus the field value.

Step 5: Unit tests for the handler

Each test method runs in its own transaction, so static variables like hotFollowUpIds and bypassedHandlers start fresh in every method.

@IsTest
private class AccountTriggerHandlerTest {

    @IsTest
    static void setDefaultRating_fillsOnlyBlankValues() {
        List<Account> accounts = new List<Account>{
            new Account(Name = 'No Rating'),
            new Account(Name = 'Has Rating', Rating = 'Cold')
        };

        AccountTriggerHandler.setDefaultRating(accounts);

        Assert.areEqual('Warm', accounts[0].Rating, 'Blank rating should default to Warm');
        Assert.areEqual('Cold', accounts[1].Rating, 'Existing rating should be kept');
    }

    @IsTest
    static void beforeUpdate_blocksClearingIndustry() {
        Account acc = new Account(Name = 'Acme', Industry = 'Banking');
        insert acc;

        acc.Industry = null;
        Test.startTest();
        Database.SaveResult result = Database.update(acc, false);
        Test.stopTest();

        Assert.isFalse(result.isSuccess(), 'Clearing Industry should fail');
    }

    @IsTest
    static void createHotFollowUps_skipsRecordsAlreadyProcessed() {
        Account acc = new Account(Name = 'Acme', Rating = 'Warm');
        insert acc;
        acc = [SELECT Id, Rating, OwnerId FROM Account WHERE Id = :acc.Id];

        Map<Id, Account> oldMap = new Map<Id, Account>{ acc.Id => acc.clone(true) };
        acc.Rating = 'Hot';

        Test.startTest();
        AccountTriggerHandler.createHotFollowUps(new List<Account>{ acc }, oldMap);
        AccountTriggerHandler.createHotFollowUps(new List<Account>{ acc }, oldMap); // simulates a re-fire
        Test.stopTest();

        Assert.areEqual(1, [SELECT COUNT() FROM Task WHERE WhatId = :acc.Id],
            'Only one Task should exist after a re-fire');
    }

    @IsTest
    static void afterUpdate_handlesMoreThan200Records() {
        List<Account> accounts = new List<Account>();
        for (Integer i = 0; i < 250; i++) {
            accounts.add(new Account(Name = 'Bulk ' + i, Rating = 'Warm'));
        }
        insert accounts;

        for (Account acc : accounts) {
            acc.Rating = 'Hot';
        }
        Test.startTest();
        update accounts;
        Test.stopTest();

        Assert.areEqual(250, [SELECT COUNT() FROM Task WHERE Subject = 'Follow up: account marked Hot'],
            'Every record across both 200-record chunks should get a Task');
    }

    @IsTest
    static void bypass_skipsHandlerLogic() {
        TriggerHandler.bypassedHandlers.add('AccountTriggerHandler');

        Account acc = new Account(Name = 'Bypassed');
        insert acc;

        acc = [SELECT Rating FROM Account WHERE Id = :acc.Id];
        Assert.isNull(acc.Rating, 'Handler should not run when bypassed');
    }
}

What each test proves:

  • In-memory test (setDefaultRating): no DML and no trigger, just the method and an assertion. This is the main payoff of the pattern.
  • DML test (beforeUpdate): confirms the validation fires through the real trigger, using Database.update(acc, false) so the test can inspect the failure.
  • Recursion test: calls the after-update logic twice with the same old values, which reproduces the workflow re-fire.
  • Bulk test: 250 records cross the 200-record chunk boundary. Swap in the Boolean flag version and this test fails, which is why it belongs in the suite.
  • Bypass test: shows the switch works, so you can trust it during data loads.

These tests also cover the trigger and both classes for deployment. Coverage is only the minimum, though. The assertions are what catch regressions. Apex Test Classes: Beyond 75% Code Coverage covers how to write tests that check behaviour instead of padding the coverage number.

Where to go from here with Salesforce Casts

If you'd rather watch the pattern being built, the free Apex Triggers Framework 101 course runs 8 episodes and about half an hour. Teja, an ex-engineer at Salesforce.com, builds the framework line by line in a real org, without slides. Every course has a GitHub repo, so you can compare your code with his.

For testing in more depth, Apex Test Fest covers async tests, System.runAs, the Assert class and callout mocks. That's what you'll need once your handlers start enqueueing jobs or calling external APIs. Apex Test Fest is part of the paid catalogue, and every plan unlocks every course.

FAQ

Do I need a trigger framework for a small org with only a few triggers?

You don't need a large framework, but even one trigger is easier to test with a handler behind it. The base class above is around 30 lines, and you write it once. Without it, splitting a trigger later means rewriting it and its tests.

Should I use an open-source framework instead of writing my own?

Kevin O'Hara's sfdc-trigger-framework and the domain layer in fflib-apex-common are both widely used. They add features such as loop counters and selector or domain classes. If your team already follows Apex Enterprise Patterns, fflib fits. Otherwise a small in-house base class like the one here is easier for new developers to read.

Can record-triggered flows and Apex triggers run on the same object?

Yes, and many orgs run both. The risk is that a flow updating the same record re-fires your update triggers, which is exactly why the recursion guard exists. Decide per object which rules live in Flow and which in Apex, and write that decision down.

How do I switch off trigger logic during a data migration?

From Apex, add the handler name to TriggerHandler.bypassedHandlers before the DML. For Data Loader jobs, where you can't run Apex first, check a hierarchy custom setting or custom metadata record inside run() and set it for the integration user only.

Why not use a single static Boolean to stop recursion?

A Boolean flag skips every chunk after the first. Triggers run in chunks of 200 records, so a 250-record update would silently skip 50 records. Track processed record Ids in a static Set<Id> instead.

Is Apex Triggers Framework 101 really free?

Yes. It's one of three free courses on Salesforce Casts, alongside JavaScript for Lightning Web Components and Salesforce Administration Training. You can watch it without buying a plan.

Next step

Copy TriggerHandler, move the logic from one of your existing triggers into a handler, and run the bulk test against it. If you'd like to watch it built first, start the free Apex Triggers Framework 101 course.


Notes on this draft:

  • Company name: I used "Salesforce Casts" throughout, not "Salesforce Casrs". That's the name in your product facts and on your page titles.
  • No citations: My web searches failed, so the platform behaviour described here comes from my own knowledge of Apex. That covers the 200-record chunks, the Trigger.old behaviour when a workflow field update re-fires a trigger, the TriggerOperation enum and the Assert class. Check these against current Salesforce documentation before you publish.
  • Code: I haven't compiled the code in an org. Deploy it to a scratch org or sandbox first.

Learn it by building it

Every course, every code repository, the discussion group and certificates of completion โ€” one subscription.

Keep me in the loop!

Email me when a new episode is published (promise, I will not spam you)

You're signing up to receive emails from Salesforce Casts