Sub topic 7
Dispatching to before and after methods
This chapter assumes you can read basic Apex (classes, methods, collections, switch). It also assumes you know the DML operations and have seen the logic-less trigger from the previous chapters. Here you will build the part of the handler that decides which method runs for a given trigger event.
The dispatch problem
A trigger that subscribes to all seven events runs the same body for every one of them. Inserting an account, updating it, deleting it, and undeleting it all enter the same code. The handler therefore has to answer one question first: which operation is happening right now?
The answer decides what the handler can safely do:
- In a before event, the record is not saved yet. You can change field values on
Trigger.newdirectly, with no DML statement. - In an after event, the record is saved and has an Id, but
Trigger.newis read-only. To change data you must run DML on other records, or on fresh copies of the same records. - In a delete event, there is no new version of the record, so
Trigger.newisnull.
Dispatching means mapping each event to a method that is written for that event. Each method gets only the context data that is valid for it.
The seven operations
Trigger.operationType returns a value of the System.TriggerOperation enum. It has one value for each event:
| Enum value | Fires | Valid context |
|---|---|---|
| `BEFORE_INSERT` | Before a new record is saved | `Trigger.new` |
| `BEFORE_UPDATE` | Before changes are saved | `Trigger.new`, `Trigger.old`, `Trigger.newMap`, `Trigger.oldMap` |
| `BEFORE_DELETE` | Before a record is deleted | `Trigger.old`, `Trigger.oldMap` |
| `AFTER_INSERT` | After a new record is saved | `Trigger.new`, `Trigger.newMap` |
| `AFTER_UPDATE` | After changes are saved | `Trigger.new`, `Trigger.old`, `Trigger.newMap`, `Trigger.oldMap` |
| `AFTER_DELETE` | After a record is deleted | `Trigger.old`, `Trigger.oldMap` |
| `AFTER_UNDELETE` | After a record is restored | `Trigger.new`, `Trigger.newMap` |
Two details in this table cause many bugs. Trigger.newMap is null in BEFORE_INSERT, because the records have no Ids yet. Trigger.new and Trigger.old are plain List<SObject>, so you must cast them to the concrete type, for example (List<Account>) Trigger.new.
How a request flows
The trigger itself stays unchanged:
trigger AccountTrigger on Account (
before insert, before update, before delete,
after insert, after update, after delete, after undelete
) {
new AccountTriggerHandler().run();
}All routing lives in run().
Dispatching with switch on the enum
Apex lets you switch on an enum value. Each when branch names one or more enum constants, and when else catches the rest.
public with sharing class AccountTriggerHandler {
public void run() {
switch on Trigger.operationType {
when BEFORE_INSERT {
beforeInsert((List<Account>) Trigger.new);
}
when BEFORE_UPDATE {
beforeUpdate((List<Account>) Trigger.new, (Map<Id, Account>) Trigger.oldMap);
}
when BEFORE_DELETE {
beforeDelete((List<Account>) Trigger.old);
}
when AFTER_INSERT {
afterInsert((List<Account>) Trigger.new);
}
when AFTER_UPDATE {
afterUpdate((List<Account>) Trigger.new, (Map<Id, Account>) Trigger.oldMap);
}
when else {
// AFTER_DELETE and AFTER_UNDELETE are not handled yet.
}
}
}
private void beforeInsert(List<Account> newAccounts) {
for (Account acc : newAccounts) {
if (String.isBlank(acc.Description)) {
acc.Description = 'Created without a description';
}
}
}
private void beforeUpdate(List<Account> newAccounts, Map<Id, Account> oldMap) {
for (Account acc : newAccounts) {
if (acc.Name != oldMap.get(acc.Id).Name) {
acc.Description = 'Renamed from ' + oldMap.get(acc.Id).Name;
}
}
}
private void beforeDelete(List<Account> oldAccounts) {
for (Account acc : oldAccounts) {
if (acc.Type == 'Customer') {
acc.addError('Customer accounts cannot be deleted.');
}
}
}
private void afterInsert(List<Account> newAccounts) {
List<Task> followUps = new List<Task>();
for (Account acc : newAccounts) {
followUps.add(new Task(WhatId = acc.Id, Subject = 'Welcome call'));
}
insert followUps;
}
private void afterUpdate(List<Account> newAccounts, Map<Id, Account> oldMap) {
// Reserved for logic that runs after an update is saved.
}
}Each method matches its event:
beforeInsertandbeforeUpdateassign fields on the records in the list. The platform saves those values, so no DML statement is needed.beforeDeletereadsTrigger.oldand callsaddErrorto block the delete.addErroris the supported way to reject a record from a trigger.afterInsertneeds the new Ids, so it runs after the save. It createsTaskrecords with a singleinsertthat sits outside the loop.
The empty afterUpdate is deliberate. It keeps the branch visible, so the next developer knows where update logic belongs.
Why the method signatures take parameters
The handler passes the cast collections as method parameters instead of letting each method read Trigger.new itself. This has three benefits:
- The signature documents what the method needs.
beforeDelete(List<Account>)tells the reader that only old values exist. - The cast happens once. Each
whenbranch converts the genericList<SObject>toList<Account>, and the private methods work with typed data. - The methods are easier to unit test and reuse. A method that takes a list does not depend on being inside a trigger. You can call it with an in-memory list in a test.
The map parameter in beforeUpdate is Trigger.oldMap. It lets you look up the previous version of a record by Id in constant time, with no query. Compare it with a nested loop over Trigger.old, which gets slower as the batch grows.
Alternative: isBefore and isAfter flags
Before Trigger.operationType existed, handlers used Boolean flags such as Trigger.isBefore, Trigger.isInsert and Trigger.isUpdate.
public void run() {
if (Trigger.isBefore) {
if (Trigger.isInsert) {
beforeInsert((List<Account>) Trigger.new);
} else if (Trigger.isUpdate) {
beforeUpdate((List<Account>) Trigger.new, (Map<Id, Account>) Trigger.oldMap);
}
} else if (Trigger.isAfter) {
if (Trigger.isInsert) {
afterInsert((List<Account>) Trigger.new);
}
}
}This works, and you will meet it in older code bases. The switch version has fewer branches and one level of nesting. It also lists the events as named constants, so a missing event stands out. Prefer switch in new code, and do not mix the two styles in one handler.
Edge cases and common mistakes
Reading context that does not exist
A method that reads the wrong collection fails at run time, not at compile time. Typical cases:
- Using
Trigger.newinbeforeDelete. It isnull, so the loop throws aNullPointerException. - Using
Trigger.newMapinbeforeInsert. It isnullbecause no Ids exist yet. - Using
Trigger.oldMapin an insert event. It isnullthere too.
Pass the correct collection in each when branch, and the method body cannot make this mistake.
Changing records in after events
If afterInsert assigns a field on a record from Trigger.new, the platform throws an exception, because those records are read-only in after events. Do the change in a before event, or re-query the record and update the copy.
Missing events silently ignored
The when else branch is empty here, so an unhandled event does nothing. That is acceptable while you build the handler, but it hides mistakes. If you add after delete to the trigger and forget the matching when, no error shows. Keep the trigger's event list and the switch branches in step, and cover each event with a test.
Running outside a trigger
Trigger.operationType is null when code runs outside a trigger context, for example when a test calls new AccountTriggerHandler().run() directly. A switch on null falls to when else, so nothing happens, and in some cases it throws. Test the handler through DML, as the testing chapter shows. Alternatively, guard run() with Trigger.isExecuting, as the base class later in this tutorial does.
Keeping the dispatch thin
The run() method should only route. If you find yourself writing an if that checks field values inside a when branch, move that check into the private method. A good dispatcher has one line per branch: a cast, then a call. This keeps the routing easy to scan, and it keeps business rules where you can name and test them. The service-layer chapter takes the next step by moving those rules out of the handler entirely.
Exercise
A developer adds after undelete to AccountTrigger and writes afterUndelete(List<Account> restored) in the handler, but never edits run(). A restored account does not get its expected follow-up task. Why, and what is the fix?
Show answer
The switch in run() has no when AFTER_UNDELETE branch, so the event falls into when else, which is empty. The method is never called. Add when AFTER_UNDELETE { afterUndelete((List<Account>) Trigger.new); }. In the undelete event, Trigger.new is valid and Trigger.old is not.
Exercise
Why does beforeDelete read Trigger.old and not Trigger.new, and what happens if it reads Trigger.new?
Show answer
A deleted record has no new version, so the platform sets Trigger.new to null in delete events. Looping over it throws a NullPointerException. Only Trigger.old and Trigger.oldMap hold data in BEFORE_DELETE and AFTER_DELETE.
Exercise
In afterInsert, a developer writes acc.Description = 'Welcome'; on each record in the list and expects it to be saved. What happens, and where should the assignment go?
Show answer
The platform rejects the change because records in Trigger.new are read-only in after events. Move the assignment to beforeInsert, where field changes on Trigger.new are saved without DML.