Sub topic 15
Moving Logic into a Handler Class
This chapter assumes you can write a trigger with several events and read Trigger.new, Trigger.oldMap and Trigger.operationType. It also assumes you know how to bulkify DML and SOQL. Here you move the trigger body into a separate class so the trigger itself is only a router.
Why a trigger body should not hold logic
A trigger file is hard to work with for three reasons:
- You cannot call it from a test without performing DML, so every check needs real database writes.
- You cannot call one trigger's code from another place, such as a Flow-invoked action or a batch job.
- Several triggers on the same object have no guaranteed run order, so their results can differ between deployments.
A handler class fixes all three. The trigger passes its context to a class, and the class holds the logic. You can unit test the class with in-memory records, and it is the single place where order is decided.
One trigger per object
Declare every event you need in a single trigger per object. Salesforce does not promise an order between separate triggers on the same object and event, so keep one and sequence the work in code.
trigger AccountTrigger on Account (
before insert, before update, before delete, after insert
) {
AccountTriggerHandler.run(
Trigger.operationType,
(List<Account>) Trigger.new,
(Map<Id, Account>) Trigger.oldMap
);
}The trigger has no if statements and no loops. It forwards three values:
Trigger.operationTypetells the handler which event fired.Trigger.newis aList<SObject>, so the trigger casts it toList<Account>.Trigger.oldMapis aMap<Id, SObject>, so the trigger casts it toMap<Id, Account>.
Casting a null value is safe. For a before insert, Trigger.oldMap is null, and the cast passes that null through.
The handler
The handler receives its context as parameters. It never reads the Trigger class itself. That is what lets a test call it directly.
public with sharing class AccountTriggerHandler {
private static final Decimal LARGE_REVENUE = 1000000;
public static void run(
System.TriggerOperation operation,
List<Account> newList,
Map<Id, Account> oldMap
) {
switch on operation {
when BEFORE_INSERT {
beforeInsert(newList);
}
when BEFORE_UPDATE {
beforeUpdate(newList, oldMap);
}
when BEFORE_DELETE {
beforeDelete(oldMap.values());
}
when AFTER_INSERT {
afterInsert(newList);
}
when else {
System.debug(LoggingLevel.WARN, 'Unhandled operation: ' + operation);
}
}
}
private static void beforeInsert(List<Account> accounts) {
for (Account a : accounts) {
if (String.isBlank(a.Description)) {
a.Description = 'Set by AccountTrigger';
}
}
}
private static void beforeUpdate(List<Account> accounts, Map<Id, Account> oldMap) {
for (Account a : accounts) {
Account oldAccount = oldMap.get(a.Id);
if (a.Phone != oldAccount.Phone) {
a.Description = 'Phone changed on ' + Date.today().format();
}
}
}
private static void beforeDelete(List<Account> accounts) {
for (Account a : accounts) {
if (a.AnnualRevenue != null && a.AnnualRevenue > LARGE_REVENUE) {
a.addError('High-revenue accounts cannot be deleted.');
}
}
}
private static void afterInsert(List<Account> accounts) {
List<Task> tasks = new List<Task>();
for (Account a : accounts) {
tasks.add(new Task(
Subject = 'Follow up with new account',
WhatId = a.Id
));
}
insert tasks;
}
}Each event gets one private method. The method bodies are the same logic you would have written inline. They stay bulk-safe: loops only touch in-memory records, and the single insert tasks sits outside the loop.
Two details are easy to miss:
beforeDeletereadsoldMap.values()becauseTrigger.newis null for delete events.Trigger.oldMapis populated for delete, so the handler does not need a separate parameter for the old list.- The
with sharingkeyword applies to the handler, not to the trigger. Triggers run in system context, but code in awith sharingclass respects the running user's sharing rules for any queries it makes. Choose the keyword on purpose.
Testing without DML
Because run takes plain parameters, a test can build unsaved records and call it. No record is written, no trigger fires, and the test runs fast.
@IsTest
private class AccountTriggerHandlerTest {
@IsTest
static void beforeInsertSetsDefaultDescription() {
List<Account> accounts = new List<Account>{
new Account(Name = 'Blank description'),
new Account(Name = 'Has description', Description = 'Keep me')
};
AccountTriggerHandler.run(System.TriggerOperation.BEFORE_INSERT, accounts, null);
System.assertEquals('Set by AccountTrigger', accounts[0].Description);
System.assertEquals('Keep me', accounts[1].Description);
}
}Keep at least one test that performs real DML as well. It proves the trigger declares the right events and passes the right values. The handler tests prove the logic, and the DML test proves the wiring.
Where recursion guards belong
Put the guard in the handler, not in the trigger, so every entry point shares it. A single static Boolean is the simplest guard, but it has a flaw. When a data load inserts more than 200 records, Salesforce runs the trigger once per chunk of 200 inside the same transaction. A Boolean set during chunk one blocks chunk two, and those records are silently skipped.
Track the Ids you have already handled instead:
public with sharing class AccountRecursionGuard {
private static Set<Id> processedIds = new Set<Id>();
public static List<Account> filterUnprocessed(List<Account> accounts) {
List<Account> fresh = new List<Account>();
for (Account a : accounts) {
if (processedIds.add(a.Id)) {
fresh.add(a);
}
}
return fresh;
}
}Set.add returns true only when the value was not already in the set, so each record passes through once per transaction. This works in after triggers, where Ids exist. Before insert records have no Id yet, so before insert logic that does not perform DML rarely needs a guard.
Common mistakes
| Mistake | Effect | Fix |
|---|---|---|
| Reading `Trigger.new` inside the handler | The handler cannot be called from a test without DML | Pass context in as parameters |
| Two triggers on one object | Run order is not guaranteed | Merge them into one trigger and one handler |
| Using `Trigger.new` in the delete branch | Null reference error | Use `Trigger.old` or `oldMap.values()` |
| A `Boolean` recursion flag | Records after the first 200 are skipped | Track processed Ids in a `Set<Id>` |
| Putting SOQL or DML in a handler loop | Governor limit errors at 200 records | Collect first, then run one query or one DML statement |
When a handler is not enough
A handler with one method per event works well until a single method grows long. At that point, move the real work into service classes, such as one that creates follow-up tasks, and have the handler call them. The handler stays a router, and the services hold the business rules. Do not split earlier than that. A trigger with one small rule gains little from three layers.
A virtual base class, with beforeInsert and similar methods that subclasses override, is a common step beyond this chapter's pattern. It removes the switch, but it hides the control flow behind inheritance. Start with the switch, which is easier to read, and move to a base class only when many objects need the same structure.
Exercise
A teammate's handler reads Trigger.new directly and the trigger has an after update event. Their new test builds an Account in memory, calls the handler, and fails with a null reference. What is the cause, and how would you change the design so the test works without DML?
Show answer
Outside a trigger, Trigger.new is null, so the handler fails when called from a test. Change run to take the records as parameters, for example run(System.TriggerOperation operation, List<Account> newList, Map<Id, Account> oldMap). The trigger passes Trigger.operationType, Trigger.new and Trigger.oldMap, and the test passes in-memory records. Keep one DML-based test to confirm the trigger itself passes the right values.
Exercise
A data load inserts 450 Accounts. The handler uses a static Boolean hasRun guard in afterInsert. How many records get follow-up tasks, and why? What would you use instead?
Show answer
Only the first 200. Salesforce processes the load in chunks of 200 within one transaction. The first chunk sets hasRun to true, and the guard then skips chunks two and three. Use a static Set<Id> of processed record Ids, and handle only records whose Id was not already in the set.