Sub topic 3
Guarding Against Repeated Trigger Execution
Assume you know basic Apex collections, DML operations, and governor limits. This chapter focuses on keeping handler work from running more than once in a transaction.
Guarding against repeated trigger execution
A trigger can fire again when its code, a flow, or another automation updates the same record. A static variable keeps its value for the current transaction. Use a static set of record IDs to remember which records the handler has processed.
public with sharing class AccountTriggerHandler {
private static Set<Id> processedIds = new Set<Id>();
public static void afterUpdate(List<Account> accounts) {
List<Account> toProcess = new List<Account>();
for (Account accountRecord : accounts) {
if (processedIds.add(accountRecord.Id)) {
toProcess.add(accountRecord);
}
}
// Process only records in toProcess.
}
}Set.add returns false when the ID already exists. This guard is transaction-scoped. It does not replace correct automation design, but it prevents accidental repeated work.
Testing the handler through DML
Test the trigger by performing DML, rather than calling private handler methods directly. This verifies the complete path from trigger to handler. Insert 200 records in one statement to test bulk behavior.
@IsTest
private class AccountTriggerHandlerTest {
@IsTest
static void bulkInsertSetsDescriptions() {
List<Account> accounts = new List<Account>();
for (Integer i = 0; i < 200; i++) {
accounts.add(new Account(Name = 'Test ' + i));
}
Test.startTest();
insert accounts;
Test.stopTest();
List<Account> saved = [
SELECT Description
FROM Account
WHERE Id IN :accounts
];
Assert.areEqual(200, saved.size());
for (Account accountRecord : saved) {
Assert.areEqual(
'Created without a description',
accountRecord.Description
);
}
}
}Handlers as thin routers over service classes
A handler should select the operation and pass records to a service class. The service class owns business rules. This separation keeps trigger-specific code small and makes business logic easier to reuse.
For example, the handler can call AccountService.createFollowUps(newAccounts). The service gathers all tasks first and performs one insert after the loop.
Extracting a base handler class
A base handler class can centralize operation dispatch and provide empty methods that subclasses override.
public virtual class TriggerHandler {
public void run() {
switch on Trigger.operationType {
when BEFORE_INSERT { beforeInsert(); }
when BEFORE_UPDATE { beforeUpdate(); }
when AFTER_INSERT { afterInsert(); }
when AFTER_UPDATE { afterUpdate(); }
when else { }
}
}
protected virtual void beforeInsert() {}
protected virtual void beforeUpdate() {}
protected virtual void afterInsert() {}
protected virtual void afterUpdate() {}
}An object-specific handler extends this class and overrides only the methods it needs.
Adding a bypass switch
A bypass switch is useful during controlled data loads or tests. Store handler names in static state, check the set before dispatching, and clear the bypass afterward.
TriggerHandler.bypass('AccountTriggerHandler');
// Perform controlled DML.
TriggerHandler.clearBypass('AccountTriggerHandler');Always clear a bypass in cleanup code so later work in the same transaction is not silently skipped.
Exercise
Why should a bulk test insert 200 records in one DML statement?
Show answer
It verifies that the trigger and handler process a full batch without performing SOQL or DML inside a loop.