Sub topic 6
Moving the work into a handler class
What this chapter assumes
You should know basic Apex syntax (classes, methods, lists, sets and maps) and what the DML operations are. You should also know what governor limits are and what Trigger.new, Trigger.oldMap and Trigger.operationType contain. The previous chapters explained why an object should have one trigger and why that trigger should contain no logic. This chapter builds the other half: the class that receives control and does the work.
The job of the handler class
A trigger file is a poor place for logic. You can't instantiate it, call its methods from a test, or extend it, and Apex gives you no way to share code between two triggers. A class has none of these limits.
A handler class is an ordinary Apex class whose job is to receive control from the trigger and carry out the work for one object. The trigger decides only that something happened. The handler decides what to do about it.
That gives each part one responsibility:
| Part | Responsibility | Contains logic? |
|---|---|---|
| Trigger | Subscribe to events, call the handler | No |
| Handler class | Choose what to do for this event and these records | Routing, plus small amounts of record-level work |
| Service class (later chapter) | Reusable business rules | Yes |
The following sequence shows what happens when a user saves an Account.
The same trigger fires twice for one insert, once before the save and once after. The handler is called both times, and it must tell the two calls apart. The next chapter covers that dispatching in detail. Here you only need to know that the handler receives control on every event.
The trigger side
The trigger subscribes to every event and calls the handler. Subscribing to all seven events costs nothing, because the handler ignores the ones it doesn't use. You then never have to edit the trigger when you add logic for a new event.
trigger AccountTrigger on Account (
before insert, before update, before delete,
after insert, after update, after delete, after undelete
) {
new AccountTriggerHandler().run();
}Three details matter here:
- The trigger creates a new handler instance on every invocation. The platform calls the trigger once per batch of up to 200 records, so one instance handles one batch.
- The trigger passes no arguments. The handler reads the context variables itself.
- The trigger name is the object name plus
Trigger. Use the same convention for the handler (AccountTriggerHandler) so the pair is easy to find.
The handler side
Here is a first working handler. It routes by operation type and implements three methods.
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
}
}Only run() is public. The handler's public surface is deliberately tiny. Everything else is private, so no other code can call a method in the wrong context.
Why the casts are needed
Trigger.new is declared as List<SObject> because the same variable serves every object type. Trigger.oldMap is a Map<Id, SObject>. The handler casts them once, at the boundary in run(). After that, every method works with Account fields directly, and the compiler checks field names. Without the cast you would write (String) rec.get('Name') everywhere.
Before and after methods do different work
The split between beforeInsert and afterInsert in the example is intentional, and it follows platform rules.
- In a before method, the records in
Trigger.newaren't saved yet. Change their fields directly and the platform saves the changes. Don't call DML on them. It isn't needed, and for the records being saved it raises an error. - In an after method, the records are saved and read-only, and they have Ids. Use after methods when you need the Id (as
afterInsertdoes forWhatId) or when you change other records.
Put each piece of work in the earliest event where it can run correctly. Field defaults and validation belong in before methods. Related-record creation belongs in after methods.
Design decisions
Instance methods, not static methods
You could write AccountTriggerHandler.run() as a static method and call it directly from the trigger. Instance methods are the better default. A handler instance can hold state for the duration of one trigger invocation, such as a list of records collected in one method and used in another. When you later extract a base class, the instance methods can be overridden. Static methods can't.
State that must outlive one invocation, such as a recursion guard, is the exception. It lives in a static variable on purpose. A later chapter covers it.
Sharing mode
A trigger runs in system mode, meaning it ignores the current user's record access. The with sharing keyword on the handler makes the handler's SOQL respect the user's sharing rules. Which choice is right depends on what the handler does. A handler that only sets defaults on Trigger.new is unaffected. A handler that queries related records to make decisions may return fewer rows for a restricted user, which can change results in a way that is hard to debug. Choose the mode deliberately and record the reason in a comment. The alternatives are without sharing and inherited sharing.
Context variables inside the handler
Because the handler is called from a trigger, Trigger.new, Trigger.oldMap and the other variables are available inside it. This is convenient, but it ties the code to trigger context. The same variables are null when the handler's code runs in any other context, such as a test that calls a private method or a batch job. The Trigger.isExecuting flag tells you whether you are in trigger context.
Read the context variables in one place, run(), and pass them to the private methods as parameters, as the example does. The private methods then depend only on their arguments, and a reader can see each method's inputs from its signature.
What stays out of the handler
A handler can grow into a second dumping ground if you let it. Three rules keep it manageable:
- The handler routes and orchestrates. A rule such as "an Account with more than 500 employees gets a different welcome task" should end up in a service class. The handler method just calls it.
- The handler never contains more than one DML statement or SOQL query per collection per method, and none inside a loop.
- The handler has no hard-coded record Ids, user names or other data that belongs in custom metadata.
For small rules, as in this chapter's examples, the logic stays inline. When a method grows past a screen of code, or the same rule is needed from a Flow-invoked action or an API class, move it out.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `System.NullPointerException` in the handler | Code reads `Trigger.new` or `Trigger.oldMap` outside trigger context, or reads `oldMap` on an insert | Read context variables only in `run()`, in the matching `when` branch. `oldMap` is `null` for insert events |
| `System.ListException: Before Insert or Upsert list must have ...` or a "record is read-only" error | DML on `Trigger.new` in a before method, or edits to `Trigger.new` in an after method | Edit fields directly in before methods. Use a separate list and DML in after methods |
| `System.TypeException: Invalid conversion from runtime type` | Casting `Trigger.new` to the wrong type | Check that the handler is called by the trigger for the matching object |
| Logic runs twice, or not at all | Two triggers exist on the object, or the handler doesn't cover the event | Confirm there is one trigger per object, and add a `when` branch for the event |
| `Too many SOQL queries: 101` on data loads | A query inside a loop in a handler method | Collect Ids into a `Set`, query once, and look results up in a `Map` |
A worked refactor
Suppose an existing trigger looks like this:
trigger AccountTrigger on Account (before insert) {
for (Account acc : Trigger.new) {
if (String.isBlank(acc.Description)) {
acc.Description = 'Created without a description';
}
}
}The refactor has four steps:
- Create
AccountTriggerHandlerwith a publicrun()method. - Move the loop into a private
beforeInsert(List<Account>)method and add theswitchbranch that calls it. - Change the trigger to subscribe to all seven events and call
new AccountTriggerHandler().run(). - Run your existing tests. The behavior is unchanged, so they should all pass.
Step 4 is the point of the refactor. It changes the structure and leaves the behavior as it was. Every later change, such as new events, bulk-safety fixes and a recursion guard, then goes into the handler where it can be reviewed and tested.
Exercise
A teammate puts update Trigger.new; at the end of beforeInsert in the handler, "to make sure the changes are saved". What happens, and what should the method do instead?
Show answer
The platform raises an error, because records in a before trigger can't be saved with DML from inside that trigger. The call is also unnecessary. In a before method, changes made directly to the fields of the records in Trigger.new are saved automatically when the trigger finishes. The method should just set the fields in the loop and return, and reserve DML for after methods that work on other records.
Exercise
The handler's afterInsert method creates a Task for each new Account. Why is insert followUps; placed after the loop instead of inside it, and why is the Task creation in an after method rather than a before method?
Show answer
One insert after the loop uses a single DML statement for up to 200 Accounts. An insert inside the loop would use one statement per Account and can exceed the 150-statement DML limit. The Task needs WhatId = acc.Id, and an Account has no Id until it is saved. Ids exist only in after methods, so the work has to happen there.