Sub topic 13
Adding a Bypass Switch for Data Loads and Tests
This chapter assumes you can write Apex classes with static members, you know how the one-trigger-per-object pattern routes work to a handler, and you know the basics of governor limits. It shows how to add a bypass switch to a base handler so you can turn handler logic off for one object during a data load or a test.
Why a bypass is useful
Sometimes the handler's work gets in the way. A one-time data migration may insert 50,000 accounts, and you may not want the "Welcome call" task created for each one. A test may need to set up records in a specific state without the before-insert defaults. A bypass lets calling code switch a handler off for a short period and then switch it back on.
A bypass is not a way to avoid fixing slow or buggy handler logic. Use it for deliberate, known cases.
How the bypass works
The base handler from the previous chapter keeps a static Set<String> named bypassed. Static state lasts for one transaction, so a bypass never leaks into another user's request or a later transaction.
The run() method works out the handler's class name and checks the set. If the name is in the set, run() returns before it dispatches anything.
public virtual class TriggerHandler {
private static Set<String> bypassed = new Set<String>();
public static void bypass(String handlerName) {
bypassed.add(handlerName);
}
public static void clearBypass(String handlerName) {
bypassed.remove(handlerName);
}
public void run() {
String description = String.valueOf(this);
String handlerName = description.substring(0, description.indexOf(':'));
if (!Trigger.isExecuting || bypassed.contains(handlerName)) {
return;
}
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() {}
}String.valueOf(this) returns text such as AccountTriggerHandler:[]. The code takes everything before the first colon as the handler name. The Trigger.isExecuting check means run() does nothing if someone calls it outside a trigger.
Using the bypass
Call bypass before the DML statement and clearBypass after it. Put the clear step in a finally block so an exception cannot leave the handler switched off for the rest of the transaction.
TriggerHandler.bypass('AccountTriggerHandler');
try {
insert migratedAccounts;
} finally {
TriggerHandler.clearBypass('AccountTriggerHandler');
}Using the bypass in tests
In a test, bypass the handler while you build fixture data, then clear it before the code under test runs. This keeps setup fast and predictable.
@IsTest
private class AccountBypassTest {
@IsTest
static void bypassedInsertSkipsDefaultDescription() {
TriggerHandler.bypass('AccountTriggerHandler');
Account acc = new Account(Name = 'Raw account');
insert acc;
TriggerHandler.clearBypass('AccountTriggerHandler');
Account saved = [SELECT Description FROM Account WHERE Id = :acc.Id];
Assert.isNull(saved.Description, 'Handler should not have run');
}
}Also keep at least one test that does not bypass anything. The bypass should not be the only path you test.
Common errors
- Forgetting to clear the bypass. The handler stays off for the rest of the transaction. Use
finally. - Misspelling the handler name. The set holds plain strings, so a typo fails silently and the handler still runs. Check that the string matches the class name exactly.
- Bypassing too broadly. Bypass only the handler you need. Other objects' handlers keep running.
- Expecting a bypass to last across transactions. Static state resets for each transaction. A Batch Apex job must set the bypass in each
executecall. - Skipping required rules. A bypassed handler also skips validation or defaulting that other code may rely on. Make sure the data you load already satisfies those rules.
Exercise
A data load script calls TriggerHandler.bypass('AccountTriggerHandler'), runs an insert that throws an exception, and catches the exception later in the same transaction. The script then updates an account. Why might the update skip the handler, and how do you prevent it?
Show answer
The exception skipped the line that calls clearBypass, so 'AccountTriggerHandler' is still in the static bypassed set and run() returns early for the later update. Put clearBypass in a finally block so it runs whether or not the insert succeeds.
Exercise
A teammate writes TriggerHandler.bypass('AccountTrigger') but the Account handler class is named AccountTriggerHandler, and the handler still runs. Why?
Show answer
The bypassed set holds exact strings, and run() compares it with the handler's class name, AccountTriggerHandler. 'AccountTrigger' does not match, so the check fails silently and dispatch continues. Use the exact class name.