Sub topic 12
Extracting a base handler class
Earlier chapters gave you a logic-less trigger, a handler class, dispatch by operation type, bulk-safe methods, a recursion guard, and tests. This chapter assumes you have read them. It also assumes you know Apex inheritance basics (virtual, override, extends) and the seven Trigger.operationType values. The goal is to move the repeated dispatch code into one shared class, so each object's handler only contains logic for that object.
Why extract a base class
AccountTriggerHandler has a run() method with a switch on Trigger.operationType. Add ContactTriggerHandler, OpportunityTriggerHandler, and CaseTriggerHandler, and each one needs the same switch. That causes three problems:
- Duplication. A fix to the dispatch logic must be copied into every handler.
- Drift. One handler forgets
AFTER_UNDELETE, another casts the wrong collection, and the handlers slowly behave differently. - No shared place for cross-cutting features. Features such as a bypass switch or logging have nowhere to live.
The solution is a virtual base class. It owns the dispatch. Each object's handler extends it and overrides only the methods it needs.
The base class
This version covers all seven operations. It also includes a small static bypass list. The mechanism is covered fully in the next chapter. It appears here because the base class is the natural place for it.
public virtual with sharing 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() {
if (!Trigger.isExecuting || bypassed.contains(getHandlerName())) {
return;
}
switch on Trigger.operationType {
when BEFORE_INSERT { beforeInsert(); }
when BEFORE_UPDATE { beforeUpdate(); }
when BEFORE_DELETE { beforeDelete(); }
when AFTER_INSERT { afterInsert(); }
when AFTER_UPDATE { afterUpdate(); }
when AFTER_DELETE { afterDelete(); }
when AFTER_UNDELETE { afterUndelete(); }
}
}
private String getHandlerName() {
String description = String.valueOf(this);
return description.substring(0, description.indexOf(':'));
}
protected virtual void beforeInsert() {}
protected virtual void beforeUpdate() {}
protected virtual void beforeDelete() {}
protected virtual void afterInsert() {}
protected virtual void afterUpdate() {}
protected virtual void afterDelete() {}
protected virtual void afterUndelete() {}
}How it works
virtualon the class. Apex classes cannot be extended unless they are declaredvirtualorabstract.virtualon the hooks. Each hook has an empty body, so a subclass overrides only the events it cares about. An unhandled event does nothing.protected. Only the class and its subclasses can call the hooks. Outside code must go throughrun().- The
Trigger.isExecutingcheck. Outside a trigger,Trigger.operationTypeisnull. Without the guard, a stray call torun()from a test or an anonymous script would fail on a nullswitchvalue. With it,run()returns quietly. getHandlerName().String.valueOf(this)on an Apex object produces text such asAccountTriggerHandler:[...]. The code takes everything before the first colon. For an inner class the name includes the outer class, for exampleOuter.Inner. Pass the same string tobypass().with sharing. The base class enforces the running user's sharing rules for queries a handler runs through inherited methods. Subclasses declare their own sharing keyword, which applies to the code they declare.
The subclass
The account handler now contains only account logic. The switch is gone, and so are the casts to Trigger.operationType values.
public with sharing class AccountTriggerHandler extends TriggerHandler {
private static Set<Id> processedIds = new Set<Id>();
protected override void beforeInsert() {
for (Account acc : (List<Account>) Trigger.new) {
if (String.isBlank(acc.Description)) {
acc.Description = 'Created without a description';
}
}
}
protected override void beforeUpdate() {
Map<Id, Account> oldMap = (Map<Id, Account>) Trigger.oldMap;
for (Account acc : (List<Account>) Trigger.new) {
if (acc.Name != oldMap.get(acc.Id).Name) {
acc.Description = 'Renamed from ' + oldMap.get(acc.Id).Name;
}
}
}
protected override void afterInsert() {
List<Task> followUps = new List<Task>();
for (Account acc : (List<Account>) Trigger.new) {
followUps.add(new Task(WhatId = acc.Id, Subject = 'Welcome call'));
}
insert followUps; // one DML statement for the whole batch
}
protected override void afterUpdate() {
List<Account> toProcess = new List<Account>();
for (Account acc : (List<Account>) Trigger.new) {
if (processedIds.add(acc.Id)) {
toProcess.add(acc);
}
}
// Work on toProcess only.
}
}The trigger file does not change:
trigger AccountTrigger on Account (
before insert, before update, before delete,
after insert, after update, after delete, after undelete
) {
new AccountTriggerHandler().run();
}Callers see the same entry point, new AccountTriggerHandler().run(). The inheritance is invisible to the trigger.
Where each responsibility lives
| Concern | Base class | Object handler |
|---|---|---|
| Choosing a method by operation type | Yes | No |
| Skipping work outside a trigger | Yes | No |
| Bypass list | Yes | No |
| Casting `Trigger.new` to the object type | No | Yes |
| Business rules and DML | No | Yes (or a service class) |
| Recursion guard state | No | Yes |
The recursion guard stays in the subclass because a Set<Id> is only meaningful per object type and per hook. A shared set in the base class would mix Account Ids with Contact Ids and would not distinguish between afterInsert and afterUpdate.
Design choices and gotchas
Casting inside every hook
Each override casts Trigger.new itself. You could make the base class store typed lists, but Apex has no generics, so the base class would only hold List<SObject>. The cast is one line, and it keeps the base class free of object-specific types.
Override signatures must match exactly
protected override void beforeInsert() must match the base method's access modifier and return type. If you write public override, Apex accepts widened access, but private override fails to compile. Keep the hook protected in subclasses so the surface stays consistent.
Bypass state is static and lasts the transaction
bypassed is a static field. It survives until the transaction ends or until you call clearBypass. If you bypass a handler and an exception happens before the clear, the handler stays off for the rest of that transaction. Use try/finally when you set a bypass.
TriggerHandler.bypass('AccountTriggerHandler');
try {
update accountsToFix;
} finally {
TriggerHandler.clearBypass('AccountTriggerHandler');
}Naming must match
bypass('AccountTriggerHandler') works only if the string equals the name derived by getHandlerName(). A typo is silent. The handler runs and nothing warns you. If this is a risk in your team, wrap names in constants.
Inheritance depth
Keep the hierarchy one level deep. If you add intermediate classes, such as a SalesTriggerHandler between the base and the handlers, each level can override hooks and call super. That makes the execution order hard to follow. Prefer composition: move shared rules into service classes that handlers call.
Testing the base class
The existing handler test still passes unchanged, because it goes through DML on 200 records. Add one test for the shared behavior. This test checks that a bypass actually prevents the handler from running.
@IsTest
private class TriggerHandlerTest {
@IsTest
static void bypassSkipsTheHandler() {
TriggerHandler.bypass('AccountTriggerHandler');
insert new Account(Name = 'Bypassed');
TriggerHandler.clearBypass('AccountTriggerHandler');
Account saved = [SELECT Description FROM Account WHERE Name = 'Bypassed'];
Assert.isNull(saved.Description, 'beforeInsert should not have run');
}
@IsTest
static void handlerRunsAfterBypassIsCleared() {
TriggerHandler.bypass('AccountTriggerHandler');
TriggerHandler.clearBypass('AccountTriggerHandler');
insert new Account(Name = 'Active');
Account saved = [SELECT Description FROM Account WHERE Name = 'Active'];
Assert.areEqual('Created without a description', saved.Description);
}
}The second test guards against a regression where clearBypass fails to re-enable the handler.
Adding a new object
With the base class in place, the steps for a new object are short:
- Create
ContactTriggerwith the seven events and one line:new ContactTriggerHandler().run();. - Create
ContactTriggerHandler extends TriggerHandler. - Override only the hooks you need.
- Write a test that performs DML on 200 records.
No dispatch code is written again.
Exercise
A teammate calls new AccountTriggerHandler().run() from an anonymous Apex script to "test" the handler. Nothing happens and no error appears. Which line of the base class causes this, and why is it there?
Show answer
The !Trigger.isExecuting check in run() returns early because the code is not running inside a trigger. It prevents a null Trigger.operationType from reaching the switch and failing. To test the handler, perform DML (for example insert accounts;) so the real trigger fires.
Exercise
You add ContactTriggerHandler extends TriggerHandler and override only afterInsert(). A Contact is updated. What does the handler do, and why?
Show answer
Nothing. run() dispatches to afterUpdate(), which is not overridden, so the empty virtual method in the base class runs. Unhandled events are safe no-ops.
Exercise
Why is the recursion guard (processedIds) kept in AccountTriggerHandler and not in the base class?
Show answer
The guard is specific to an object type and hook. A single shared set in the base class would mix Ids from different objects and could not tell afterInsert from afterUpdate. Keeping it in the subclass lets each handler guard exactly what it needs.