Sub topic 7
Structuring bulk-safe triggers and handlers
This chapter assumes you can read Apex syntax and use Lists, Sets and Maps. It also assumes you know the basics of SOQL and DML, and the before and after trigger events. Earlier chapters showed how to remove queries and DML from loops. Here you organize that code so it stays bulk-safe as it grows.
Why structure matters
A trigger always receives a batch. Trigger.new can hold up to 200 records, and the whole batch shares one set of governor limits. If trigger logic is scattered across several triggers on one object, you lose control of two things:
- Execution order. Salesforce does not guarantee the order of multiple triggers on the same object and event.
- Shared limits. Every trigger in the transaction draws from the same query and DML budget, so duplicated queries add up.
The standard answer is one trigger per object. The trigger contains no business logic. It only checks the context and passes collections to a handler class.
The trigger: routing only
trigger AccountTrigger on Account (before insert, before update, after insert) {
if (Trigger.isBefore) {
AccountTriggerHandler.beforeSave(Trigger.new, Trigger.oldMap);
} else if (Trigger.isAfter && Trigger.isInsert) {
AccountTriggerHandler.afterInsert(Trigger.new);
}
}The trigger passes whole collections, never single records. Trigger.oldMap is null on insert, so the handler must allow for that.
The handler: logic on collections
public with sharing class AccountTriggerHandler {
public static void beforeSave(List<Account> newRecords, Map<Id, Account> oldMap) {
for (Account a : newRecords) {
Boolean isUpdate = oldMap != null && oldMap.containsKey(a.Id);
Boolean industryChanged = isUpdate && oldMap.get(a.Id).Industry != a.Industry;
if (a.Industry == null && (!isUpdate || industryChanged)) {
a.Industry = 'Other';
}
}
}
public static void afterInsert(List<Account> newRecords) {
List<Task> tasks = new List<Task>();
for (Account a : newRecords) {
tasks.add(new Task(WhatId = a.Id, Subject = 'Follow up'));
}
if (!tasks.isEmpty()) {
insert tasks;
}
}
}Three habits make this handler bulk-safe:
- Method signatures take collections. A method named
beforeSave(Account a)invites a call inside a loop. A method takingList<Account>does not. - Queries and DML sit outside per-record loops. Each handler method does its work in one pass and runs DML once at the end.
oldMapis used for change detection. You compare old and new values by Id instead of querying the record again.
The before method changes Industry directly on the records in newRecords. Before triggers need no DML to save those changes. Calling update there would waste a DML statement and can cause errors.
How the pieces fit
Common mistakes
- A handler method that queries inside its own loop. Moving code into a class does not make it bulk-safe. The structure only helps if the method body is also free of loops that call SOQL or DML.
- Reading
Trigger.new[0]only. This processes one record and silently skips the other 199. - Not handling
nullforoldMap. CallingoldMap.get(...)during an insert throws aNullPointerException. - Putting logic in the trigger file. Trigger bodies are hard to unit test in isolation and tend to grow into one long block.
Exercise
The handler method afterInsert(List<Account> newRecords) is called from a trigger that fires when 200 Accounts are inserted in one operation. How many DML statements does the method use, and what would change if the insert tasks; line were moved inside the for loop?
Show answer
It uses one DML statement, because all 200 Tasks are collected in a List and inserted together. If the insert moved inside the loop, it would run 200 times in the same transaction. That exceeds the limit of 150 DML statements per transaction and throws a System.LimitException.