Sub topic 10
Keeping guards in a trigger handler class
This chapter assumes you can write a basic Apex trigger, use List, Set, and Map, and issue DML statements. It also assumes you know that static variables keep their value for one transaction, and that you have seen the static Set<Id> guard from the previous chapter. Here you will move that guard out of the trigger and into a handler class, so the guard lives in one place that you can read, reuse, and test.
Why guards belong in a handler class
A trigger file is a poor place for logic. A trigger cannot hold static variables or helper methods of its own. Triggers cannot be called directly from tests except by performing DML. Every guard you write inside the trigger body is tied to that one file and is hard to test on its own.
A handler class fixes this. The trigger becomes a thin router. It checks which event fired and passes the right data to a method on the handler. The handler holds the static state, the guard logic, and the business logic.
This gives you four practical benefits:
- One guard location. The static variable and the code that reads it sit next to each other in one class.
- Testability. You can call handler methods directly with lists you build in memory, and also test through real DML.
- Readability. The trigger shows the events it handles. The handler shows what happens for each event.
- Reuse. If several triggers or services need the same guard, they share one class.
The thin trigger
The trigger checks the context and delegates. It does no work itself.
trigger AccountTrigger on Account (after update) {
if (Trigger.isAfter && Trigger.isUpdate) {
AccountTriggerHandler.afterUpdate(Trigger.new);
}
}The Trigger.isAfter && Trigger.isUpdate check is redundant here, because the trigger only declares after update. It becomes useful when the trigger lists several events, such as before insert, before update, after update. Keeping the check from the start means you do not have to rewrite it when you add events later.
The handler with a Set of Ids guard
The handler holds a private static Set<Id>. Because the set is static, it keeps its contents for the whole transaction. A re-fired trigger calls the same method, sees the Ids already in the set, and skips those records.
public class AccountTriggerHandler {
private static Set<Id> processedIds = new Set<Id>();
public static void afterUpdate(List<Account> newList) {
List<Account> toUpdate = new List<Account>();
for (Account acc : newList) {
if (processedIds.contains(acc.Id)) {
continue;
}
processedIds.add(acc.Id);
toUpdate.add(new Account(Id = acc.Id, Description = 'Reviewed'));
}
if (!toUpdate.isEmpty()) {
update toUpdate;
}
}
}Follow what happens when one account is updated:
- The update fires the trigger. The handler sees the Id is new, adds it to
processedIds, and issues anupdate. - That
updatefires the trigger again, in the same transaction. The handler finds the Id in the set and skips it. toUpdateis empty, so no DML runs and the recursion stops.
The guard checks and records each Id before the DML statement. This order matters. If you add the Ids after the update, the re-fired trigger runs before the set is populated and the guard never takes effect.
The if (!toUpdate.isEmpty()) check avoids a DML statement on an empty list. An empty update does not fail, but it still counts as a DML statement, and in the re-fired call it would also run a pointless extra pass.
Why a Set of Ids is safer than a Boolean here
The handler could use a single Boolean hasRun instead. That works for a single record, but it fails when a bulk operation passes more than 200 records. Salesforce hands the trigger records in chunks of 200 within one transaction, and a static Boolean set during the first chunk makes the trigger skip every later chunk. The Set of Ids avoids this, because each chunk contains different Ids and each Id is processed once.
The cost is memory. The set grows with the number of records processed. For typical trigger volumes this is small, but a transaction that touches tens of thousands of records holds that many Ids in the heap. This is rarely a problem, and the heap limit is worth keeping in mind for very large operations.
Separating routing, guarding, and logic
As the handler grows, a single method that does everything becomes hard to read. A common refinement is to split the guard from the business logic. The public method decides which records to process. A private method does the work on those records.
public class AccountTriggerHandler {
private static Set<Id> processedIds = new Set<Id>();
public static void afterUpdate(List<Account> newList, Map<Id, Account> oldMap) {
List<Account> toProcess = new List<Account>();
for (Account acc : newList) {
if (processedIds.contains(acc.Id)) {
continue;
}
Account oldAcc = oldMap.get(acc.Id);
if (acc.Rating != oldAcc.Rating) {
processedIds.add(acc.Id);
toProcess.add(acc);
}
}
if (!toProcess.isEmpty()) {
markReviewed(toProcess);
}
}
private static void markReviewed(List<Account> accounts) {
List<Account> toUpdate = new List<Account>();
for (Account acc : accounts) {
toUpdate.add(new Account(Id = acc.Id, Description = 'Reviewed'));
}
update toUpdate;
}
}The trigger passes both lists:
trigger AccountTrigger on Account (after update) {
if (Trigger.isAfter && Trigger.isUpdate) {
AccountTriggerHandler.afterUpdate(Trigger.new, Trigger.oldMap);
}
}This version combines two defenses. The changed-field check selects only records whose Rating changed. The Set of Ids ensures each of those records is handled once per transaction. Note that the Id is added to the set only when the record qualifies. A record whose Rating has not changed is not marked as processed, so if a later change in the same transaction does alter its Rating, it still gets handled.
Keeping the guard private
Declare the static variable private. If other classes can write to it, they can reset or fill the set and change when your logic runs, and the failures are hard to trace. When another class legitimately needs to influence the guard, expose a small, named method instead of the variable itself. The next chapter covers a bypass switch, which is one such method.
A handler also works best when it has no hidden dependencies on trigger context. Passing Trigger.new and Trigger.oldMap in as parameters, instead of reading Trigger.new inside the handler, lets you call the method from a test with records you built yourself.
Common mistakes
| Mistake | What happens | Fix |
|---|---|---|
| Putting the guard variable in the trigger | Triggers cannot declare static variables, so the code does not compile. | Declare the static variable in the handler class. |
| Marking Ids as processed after the DML | The re-fired trigger runs before the set is filled and recurses. | Add the Id to the set before issuing DML. |
| Adding every Id, not only processed ones | A later real change to the same record in the transaction is skipped. | Add an Id only when the logic runs for that record. |
| Using `public static` for the guard | Other code can clear or fill it and change behavior silently. | Use `private static` and expose a named method if needed. |
| Reading `Trigger.new` inside the handler | The method cannot be unit tested without DML. | Pass the lists in as parameters. |
| Using a Boolean in a bulk-capable trigger | Records beyond the first chunk of 200 are skipped. | Use a `Set<Id>`. |
Seeing the flow
The diagram shows how one update moves between the trigger, the handler, and the guard.
Testing through the handler
A handler class gives you two ways to test. Testing through DML confirms the whole path, including that the trigger does not hit a depth error:
@IsTest
private class AccountTriggerHandlerTest {
@IsTest
static void updateRunsGuardedLogicWithoutDepthError() {
Account acc = new Account(Name = 'Test Account');
insert acc;
Test.startTest();
acc.Rating = 'Hot';
update acc;
Test.stopTest();
Account result = [SELECT Description FROM Account WHERE Id = :acc.Id];
System.assertEquals('Reviewed', result.Description);
}
}Calling the handler directly lets you check the guard in isolation. For example, you can call afterUpdate twice with the same list and confirm the second call does nothing. The next chapters build on this when they cover testing recursion guards in detail.
Limits of the pattern
A handler class with a static guard protects one transaction. The static state is discarded when the transaction ends. If your logic enqueues a Queueable job, calls a future method, or runs in a batch, that work starts a new transaction with fresh static variables, and the guard does not carry over. Later chapters cover that boundary.
The pattern also does not decide which strategy is right. A before trigger that changes Trigger.new directly needs no guard at all, and a changed-field check is often simpler than a set. Use the handler to organize whichever strategy you choose.
Exercise
Your handler's afterUpdate method adds every Id from newList to the static Set<Id> at the top of the loop, then checks whether the Rating changed. A user updates an account's Name, and later in the same transaction a flow changes that account's Rating. Why might the Rating logic never run, and how do you fix it?
Show answer
The first update adds the Id to the set even though the Rating did not change and the logic did not run. When the flow changes the Rating and the trigger fires again, the guard finds the Id in the set and skips the record. Fix it by checking the changed-field condition first and adding the Id to the set only when the record qualifies and the logic is about to run.
Exercise
Why can a trigger not hold a recursion guard as a static variable, and where should the variable go instead?
Show answer
Apex triggers cannot declare static variables or helper methods, so the code would not compile. Put the guard in a handler class as a private static variable, and have the trigger call a method on that class.