Sub topic 12
Extracting a base handler class
This chapter assumes you can write an Apex trigger that calls a handler class. It also assumes you know Trigger.operationType and switch on, and that you have seen a static recursion guard. If a second or third object now needs a handler, you will probably copy the same dispatch code into each one. A base class removes that copy.
What repeats across handlers
Every handler you have written so far does the same three things:
- It checks that it is running inside a trigger.
- It switches on
Trigger.operationType. - It calls a method for the matching event.
Only the method bodies differ between objects. Code that stays the same belongs in a parent class. Code that changes belongs in the child.
The base class
The base class is marked virtual so other classes can extend it. It owns run(), the dispatch, and a static bypass list. Each event method is protected virtual with an empty body, so a child that ignores an event does nothing for it.
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 keeps the part before the first colon as the handler's name. That name is the key for the bypass list.
The Trigger.isExecuting check makes run() do nothing when called outside a trigger. That keeps a stray call from a test or a script from failing on empty context variables.
A child handler
The child extends the base and overrides only what it needs. Each override must say override. The trigger itself does not change.
public with sharing class AccountTriggerHandler extends TriggerHandler {
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 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;
}
}trigger AccountTrigger on Account (
before insert, before update, before delete,
after insert, after update, after delete, after undelete
) {
new AccountTriggerHandler().run();
}A new ContactTriggerHandler needs only its own overrides. Bulk safety is still your job in each override. The base class cannot stop you from putting a query or DML statement inside a loop.
Using the bypass switch
Call bypass before an operation that should skip a handler, such as a data load or a test that sets up records. Call clearBypass in a finally block so an exception cannot leave the handler switched off.
TriggerHandler.bypass('AccountTriggerHandler');
try {
insert new Account(Name = 'Loaded without trigger logic');
} finally {
TriggerHandler.clearBypass('AccountTriggerHandler');
}Common errors
- Missing
override. The compiler rejects a child method that has the same name as a parent method but nooverridekeyword. - Wrong visibility. An override cannot be less visible than the method it replaces. Use
protected override, notprivate override. - Bypass name mismatch. The name is the class name, spelled exactly. A typo makes
bypasssilently do nothing. - Unhandled events. The base class here dispatches four events. Delete, undelete and the other before and after events fall into
when else. Add awhenbranch and a virtual method for each one you need.
Exercise
You add a before delete check to AccountTriggerHandler by writing protected override void beforeDelete() { ... }, but it never runs. The trigger already subscribes to before delete. What is missing in the base class, and what must you add to it?
Show answer
The base class has no beforeDelete method, so the override would not compile as written, and run() has no when BEFORE_DELETE branch to call it. Add protected virtual void beforeDelete() {} and a when BEFORE_DELETE { beforeDelete(); } branch in the switch on Trigger.operationType block. After that, the child's override runs on deletes.