Sub topic 12
Keeping the trigger thin with a handler class
This chapter assumes you can read Apex, know the trigger context variables (Trigger.new, Trigger.oldMap), and have seen the bulk SOQL and DML patterns from earlier chapters. Here you will move logic out of the trigger body and into a handler class.
Why keep the trigger thin
A trigger file can only hold trigger code. It cannot declare static helper methods you can call from tests, and logic written inline is hard to unit test, reuse, or read. A thin trigger has one job: pass the context to a class. The class then does the work.
A handler class gives you three benefits:
- Methods take plain
ListandMapparameters, so tests can call them without firing a trigger. - Bulk logic lives in one place, so SOQL and DML stay outside loops.
- One trigger per object keeps the order of execution predictable. Several triggers on the same object run in no guaranteed order.
The pattern
The trigger passes Trigger.new and Trigger.oldMap to a static method. The handler compares old and new stage values and collects all new Task records in a list. It then inserts the list once.
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;
}
}
}In a real project the handler goes in its own file, OpportunityTriggerHandler.cls. It is shown together with the trigger here for reading.
How the handler works
The handler does four things:
- It receives the whole batch of up to 200 records, not one record.
- It checks
oldMap != null. On insert,Trigger.oldMapisnull, so callingoldMap.get(...)without a check would throw aNullPointerException. - It acts only when the stage changed to
Closed Won. This is the change-detection pattern from the previous chapter. - It runs
insert tasksonce, after the loop, and skips the DML when the list is empty.
The trigger uses the after context because the Task needs opp.Id, which exists only after insert.
Common mistakes
- Passing a single record to the handler. A method that takes one
Opportunityinvites a query or DML inside the caller's loop. Pass collections. - Several triggers on one object. Their order is not guaranteed. Use one trigger per object and branch on context inside it.
- Skipping the null check on
oldMap. It isnullon insert and undelete. - Using
without sharingby default. Declarewith sharingunless you have a documented reason not to.
Exercise
Why does the handler check oldMap != null before calling oldMap.get(opp.Id)?
Show answer
On insert, Trigger.oldMap is null because no earlier version of the record exists. Calling get on it would throw a NullPointerException. The check makes the same handler safe for both insert and update.
Exercise
The handler needs to set a field on each record being saved, with no related records involved. Which trigger context should you use, and does the handler need DML?
Show answer
Use a before trigger. Changes made to Trigger.new records in a before context are saved automatically, so the handler needs no DML statement.