Sub topic 12
Keeping the Trigger Thin with a Handler Class
This chapter assumes you can write basic Apex classes and methods, know the trigger context variables (Trigger.new, Trigger.oldMap), and understand why triggers must handle lists of up to 200 records. It shows how to move trigger logic into a handler class so the logic is easier to test, read, and reuse.
Why a trigger should be thin
A trigger file is an entry point. Salesforce calls it when a record event happens. It is a poor place to keep business rules, for four reasons.
- A trigger cannot declare methods that other code can call. Logic written inline cannot be reused from a batch job or a controller.
- A trigger cannot be unit tested one piece at a time. To test any rule you have to run a full DML operation.
- A trigger with several events (
before insert,after update, and so on) grows long and full ofifbranches. - Several triggers on the same object have no guaranteed order of execution. A single trigger per object that delegates to one handler gives you control over the order.
A thin trigger contains no business logic. It decides which handler method to call for the current context and passes in the data the handler needs.
The handler class pattern
A handler is an ordinary Apex class. Its methods take collections as parameters, not the Trigger context variables themselves. Taking plain lists and maps has three benefits.
- The method is bulk-safe by design, because its signature forces you to think in lists.
- A test can call the method directly with records that were never saved.
- The method does not depend on being called from a trigger.
Here is the trigger and handler for an Opportunity. When an opportunity moves to Closed Won, the handler creates a follow-up task.
trigger OpportunityTrigger on Opportunity (after insert, after update) {
OpportunityTriggerHandler.createFollowUpTasks(Trigger.new, Trigger.oldMap);
}
public with sharing class OpportunityTriggerHandler {
public static void createFollowUpTasks(
List<Opportunity> newOpps,
Map<Id, Opportunity> oldMap
) {
List<Task> tasks = new List<Task>();
for (Opportunity opp : newOpps) {
Boolean isWon = opp.StageName == 'Closed Won';
Boolean wasWon = oldMap != null
&& oldMap.get(opp.Id).StageName == 'Closed Won';
if (isWon && !wasWon) {
tasks.add(new Task(
Subject = 'Send welcome package',
WhatId = opp.Id,
OwnerId = opp.OwnerId
));
}
}
if (!tasks.isEmpty()) {
insert tasks;
}
}
}Three details in this handler matter.
- The
oldMapnull check. On insert,Trigger.oldMapisnull. CallingoldMap.get(...)without the check would throw aNullPointerExceptionon the first opportunity inserted asClosed Won. The expressionoldMap != null && ...short-circuits, sowasWonisfalseon insert. - The change check.
isWon && !wasWonacts only on records that just became won. An update to the description of an already-won opportunity creates no task. - One DML statement. The loop only builds the list. A single
insert tasksruns after the loop, so 200 won opportunities use one DML statement, not 200.
The with sharing keyword makes the handler respect the running user's record access. Choose it deliberately. If a handler must see records the user cannot, use without sharing or inherited sharing and document why.
Dispatching by context
Most real triggers handle several events. The trigger file then decides which handler method runs, using the context flags.
trigger OpportunityTrigger on Opportunity (
before insert, before update, after insert, after update
) {
if (Trigger.isBefore) {
if (Trigger.isInsert) {
OpportunityTriggerHandler.beforeInsert(Trigger.new);
} else if (Trigger.isUpdate) {
OpportunityTriggerHandler.beforeUpdate(Trigger.new, Trigger.oldMap);
}
} else if (Trigger.isAfter) {
if (Trigger.isInsert) {
OpportunityTriggerHandler.afterInsert(Trigger.new);
} else if (Trigger.isUpdate) {
OpportunityTriggerHandler.afterUpdate(Trigger.new, Trigger.oldMap);
}
}
}
public with sharing class OpportunityTriggerHandler {
public static void beforeInsert(List<Opportunity> newOpps) {
for (Opportunity opp : newOpps) {
if (String.isBlank(opp.Description)) {
opp.Description = 'No description provided';
}
}
}
public static void beforeUpdate(
List<Opportunity> newOpps,
Map<Id, Opportunity> oldMap
) {
// Field validation or defaults for updates go here.
}
public static void afterInsert(List<Opportunity> newOpps) {
createFollowUpTasks(newOpps, null);
}
public static void afterUpdate(
List<Opportunity> newOpps,
Map<Id, Opportunity> oldMap
) {
createFollowUpTasks(newOpps, oldMap);
}
public static void createFollowUpTasks(
List<Opportunity> newOpps,
Map<Id, Opportunity> oldMap
) {
List<Task> tasks = new List<Task>();
for (Opportunity opp : newOpps) {
Boolean isWon = opp.StageName == 'Closed Won';
Boolean wasWon = oldMap != null
&& oldMap.get(opp.Id).StageName == 'Closed Won';
if (isWon && !wasWon) {
tasks.add(new Task(
Subject = 'Send welcome package',
WhatId = opp.Id,
OwnerId = opp.OwnerId
));
}
}
if (!tasks.isEmpty()) {
insert tasks;
}
}
}The before methods edit Trigger.new records directly. No DML is needed, because the changes are saved with the record. The after methods create related records, because the saved record has an Id by then. This follows the before and after rules from earlier in the tutorial.
Notice that the trigger file has branches but no rules. If a requirement changes, you edit the handler and leave the trigger alone.
How the pieces connect
The diagram shows how one save operation reaches the handler and what the handler does with the collections it receives.
Passing the right data
Pass the smallest data the handler needs. Some guidelines follow.
- Pass collections, not the context. A method that accepts
List<Opportunity>is easy to test. A method that readsTrigger.newinside itself cannot be called from a test without a real DML operation. - Pass
oldMaponly when the logic compares values. Insert-only logic does not need it. - Do not store the context in static fields unless you have a reason. Static state lives for the whole transaction and can leak between trigger invocations.
- Keep queries inside the handler, and run each one once per method call. The handler is where the collect, query, and look up steps from the bulk SOQL chapter belong.
Common errors
| Mistake | What happens | Fix |
|---|---|---|
| Handler reads `Trigger.new` directly | The method fails or does nothing when called from a test | Pass the list as a parameter |
| Missing `oldMap != null` check | `NullPointerException` on insert | Check for `null` before `oldMap.get` |
| Business logic left in the trigger | Logic cannot be reused or tested alone | Move it to a handler method |
| Two triggers on one object | Execution order is not guaranteed | Keep one trigger per object |
| Handler method takes a single record | Callers loop and run SOQL or DML once per record | Take `List<SObject>` or `Map<Id, SObject>` |
| DML inside the handler's loop | Hits the DML limit at 150 statements | Build a list, then run one DML after the loop |
Testing the handler
Because the handler takes lists, you can test a method without saving anything. The test below builds opportunities in memory and passes them to the handler. Since the handler inserts tasks, the opportunities need real IDs, so the test inserts them first.
@IsTest
private class OpportunityTriggerHandlerTest {
@IsTest
static void createsTaskOnlyForNewlyWonOpportunity() {
Opportunity opp = new Opportunity(
Name = 'Handler test',
StageName = 'Prospecting',
CloseDate = Date.today().addDays(30)
);
insert opp;
Opportunity oldOpp = opp.clone(true);
opp.StageName = 'Closed Won';
Test.startTest();
OpportunityTriggerHandler.createFollowUpTasks(
new List<Opportunity>{ opp },
new Map<Id, Opportunity>{ oldOpp.Id => oldOpp }
);
Test.stopTest();
Integer taskCount = [SELECT COUNT() FROM Task WHERE WhatId = :opp.Id];
System.assertEquals(1, taskCount, 'Expected one follow-up task');
}
}This test calls the handler directly, so it checks the rule without relying on a trigger firing. You should still keep a bulk test that updates 200 records through DML. That test confirms the trigger and handler work together within governor limits.
Edge cases to watch
- Recursion. If the handler updates records of the same object, the trigger fires again. Guard against it with a static
Set<Id>of processed IDs, covered in the recursion chapter. - Static methods versus instances. Static handler methods are simple, but they are harder to replace in tests. If you need to mock behavior, use instance methods and an interface. For most triggers, static methods are enough.
- Handler size. If one handler grows past a few hundred lines, split it by concern, for example one class for task creation and one for field defaults. The trigger can call both.
Exercises
Exercise
A handler method is declared as public static void process() and reads Trigger.new inside. Give two problems with this design and how to fix them.
Show answer
The method cannot be called from a test without firing a real trigger through DML, and it works only inside a trigger context, so other code cannot reuse it. Fix it by declaring process(List<Opportunity> newOpps, Map<Id, Opportunity> oldMap) and having the trigger pass Trigger.new and Trigger.oldMap.
Exercise
In afterInsert, the handler calls createFollowUpTasks(newOpps, null). Why does this not throw an error, and what would happen if the oldMap != null check were removed?
Show answer
The expression oldMap != null && ... short-circuits, so oldMap.get is never called when oldMap is null, and wasWon is false. Without the check, the first Closed Won opportunity in an insert would cause a NullPointerException.
Exercise
A teammate adds a second trigger on Opportunity for a new requirement. Why is this risky, and what should they do instead?
Show answer
Salesforce does not guarantee the order in which multiple triggers on the same object run, so results can differ between runs and one trigger may see the other's changes unpredictably. They should add a new handler method (or a new handler class) and call it from the existing single trigger.