Sub topic 6
Moving the Work into a Handler Class
This chapter assumes you know basic Apex syntax (classes, methods, collections), what DML operations are, and that governor limits exist. It also assumes you have seen the one-trigger-per-object rule. Here you move the logic out of the trigger body and into a handler class.
Why a handler class
A trigger is a poor place to keep logic. You can't instantiate it, call its parts from a test, or reuse its code. A trigger body that grows past a few lines also becomes hard to read.
A handler class is an ordinary Apex class. It holds the logic, and the trigger only calls it. This gives you:
- Methods you can read, name, and change one at a time.
- Code you can test through normal DML.
- A single place to look when an object behaves oddly.
The logic-less trigger
The trigger subscribes to every event and does nothing else. It creates the handler and calls run().
trigger AccountTrigger on Account (
before insert, before update, before delete,
after insert, after update, after delete, after undelete
) {
new AccountTriggerHandler().run();
}Subscribing to all seven events costs nothing. The handler decides which events it cares about. When you later need to handle another event, you edit the handler and leave the trigger alone.
The handler class
The handler reads the context variables, picks a method by operation type, and passes it correctly typed collections. Trigger.new and Trigger.oldMap are declared with generic types, so you cast them to Account types.
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 AFTER_INSERT {
afterInsert((List<Account>) Trigger.new);
}
when else {
// Other operations 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 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; // one DML statement for the whole batch
}
}The flow of a save looks like this:
What to notice
- Before methods change records directly. In
beforeInsert, settingacc.Descriptionneeds no DML. The values are saved with the record. Callingupdatein a before trigger is a common mistake. - After methods create related data. Records have Ids in
afterInsert, so you can useacc.IdasWhatId. Fields onTrigger.neware read-only in after triggers. - Each method takes a collection. The trigger fires once for up to 200 records, so every method loops over the whole list.
- DML sits outside the loop.
afterInsertbuilds a list and inserts it once. Puttinginsertinside the loop would use one DML statement per record and hit the limit of 150 DML statements. with sharingis explicit. Triggers run in system context, but the handler's sharing keyword controls how code it calls enforces record sharing. State your choice instead of relying on defaults.
Common errors
| Symptom | Likely cause |
|---|---|
| `System.TypeException: Invalid conversion` | Cast to the wrong type, for example `Trigger.new` to `List<Contact>` inside the Account handler |
| `NullPointerException` on `Trigger.oldMap` | Reading `oldMap` on insert, where it is null |
| `Too many DML statements: 151` | `insert` or `update` placed inside a loop |
| Field change has no effect | Assigning to `Trigger.new` fields in an after trigger, which is read-only |
Exercise
In the handler above, why does afterInsert build a List<Task> and call insert once after the loop, instead of inserting each Task inside the loop?
Show answer
A trigger can receive up to 200 records in one execution. Inserting inside the loop would run one DML statement per record and exceed the limit of 150 DML statements per transaction. A single insert on the list uses one DML statement however many records the batch holds.
Exercise
You add a beforeDelete event to the work. The trigger already lists before delete. Which file do you change, and what do you add there?
Show answer
Change only the handler. Add a when BEFORE_DELETE branch to the switch in run(), and write a beforeDelete method that takes Trigger.old or Trigger.oldMap, cast to Account types. The trigger body stays the same.