Sub topic 7
Structuring Bulk-Safe Triggers and Handlers
This chapter assumes you know basic Apex syntax, the List, Set and Map collections, SOQL and DML, and the before and after trigger events. It builds on the previous chapters: triggers receive up to 200 records at a time, and queries and DML belong outside loops. Here the question is how to organize a trigger so those rules are easy to follow and hard to break.
Why trigger structure matters
A trigger is a poor place for logic. The code is hard to unit test, you cannot call it from anywhere else, and logic for several features tends to pile up in one file. That pile is where bulk bugs hide. A query added by one developer in line 80 ends up inside a loop added by another developer in line 40.
Two conventions fix most of this:
- One trigger per object. Salesforce does not guarantee the order in which multiple triggers on the same object and event run. Several triggers also make limit usage hard to reason about, because they all share one transaction's limits.
- A thin trigger that does no work itself. It decides which event happened and passes the collections to a handler class.
The trigger context variables
A trigger sees the whole batch through context variables. These are the ones you use when structuring a handler.
| Variable | Type | Available in |
|---|---|---|
| `Trigger.new` | `List<SObject>` | insert, update, undelete |
| `Trigger.old` | `List<SObject>` | update, delete |
| `Trigger.newMap` | `Map<Id, SObject>` | after insert, before update, after update, after undelete |
| `Trigger.oldMap` | `Map<Id, SObject>` | update, delete |
| `Trigger.isBefore`, `Trigger.isAfter` | `Boolean` | all events |
| `Trigger.operationType` | `System.TriggerOperation` enum | all events |
Two details cause common errors:
- In a before insert trigger, records have no Id yet, so
Trigger.newMapisnull. Code that callsTrigger.newMap.get(...)there throws aNullPointerException. Trigger.newis read-only in after triggers. Assigning to a field on a record inTrigger.newthrows an error in an after trigger. In a before trigger you may change fields directly, and Salesforce saves the changes without a DML statement.
A thin trigger
Trigger.operationType returns an enum, so a switch statement covers every event cleanly. The trigger below contains no business logic.
trigger ContactTrigger on Contact (
before insert, before update,
after insert, after update
) {
switch on Trigger.operationType {
when BEFORE_INSERT {
ContactTriggerHandler.beforeInsert(Trigger.new);
}
when BEFORE_UPDATE {
ContactTriggerHandler.beforeUpdate(Trigger.new, Trigger.oldMap);
}
when AFTER_INSERT {
ContactTriggerHandler.afterInsert(Trigger.new);
}
when AFTER_UPDATE {
ContactTriggerHandler.afterUpdate(Trigger.new, Trigger.oldMap);
}
when else {
// Events this trigger is not subscribed to never arrive here.
}
}
}The trigger passes collections, never single records. Every handler method accepts a List or a Map, so a method that processes one record at a time cannot be called by accident.
A handler class
The handler holds the logic. Each method follows the same three steps:
- Collect the keys you need from the batch into a Set.
- Query once, and put the results in a Map.
- Loop over the batch, look up related data in the Map, and gather records for DML in a List.
The handler below sets a description from the parent account's industry. It also creates a follow-up task when a contact's email changes.
public with sharing class ContactTriggerHandler {
public static void beforeInsert(List<Contact> newContacts) {
setIndustryDescription(newContacts);
}
public static void beforeUpdate(
List<Contact> newContacts,
Map<Id, Contact> oldMap
) {
setIndustryDescription(newContacts);
}
public static void afterInsert(List<Contact> newContacts) {
// Reserved for future logic.
}
public static void afterUpdate(
List<Contact> newContacts,
Map<Id, Contact> oldMap
) {
createTasksForChangedEmails(newContacts, oldMap);
}
private static void setIndustryDescription(List<Contact> contacts) {
Set<Id> accountIds = new Set<Id>();
for (Contact c : contacts) {
if (c.AccountId != null) {
accountIds.add(c.AccountId);
}
}
if (accountIds.isEmpty()) {
return;
}
Map<Id, Account> accounts = new Map<Id, Account>(
[SELECT Id, Industry FROM Account WHERE Id IN :accountIds]
);
for (Contact c : contacts) {
Account a = accounts.get(c.AccountId);
if (a != null) {
c.Description = 'Industry: ' + a.Industry;
}
}
}
private static void createTasksForChangedEmails(
List<Contact> newContacts,
Map<Id, Contact> oldMap
) {
List<Task> tasks = new List<Task>();
for (Contact c : newContacts) {
Contact oldContact = oldMap.get(c.Id);
if (c.Email != oldContact.Email) {
tasks.add(new Task(
WhoId = c.Id,
Subject = 'Verify new email address'
));
}
}
if (!tasks.isEmpty()) {
insert tasks;
}
}
}Points worth noticing:
- The query runs only if
accountIdsis not empty. This saves a query, which counts against the limit of 100 synchronous SOQL queries even when it returns nothing. accounts.get(c.AccountId)returnsnullwhen the key is missing, so thenullcheck is required. Contacts without an account hit this case.- The handler compares each record against
oldMapto act only on records that changed. This keeps DML and CPU use proportional to the real change, not to the batch size. with sharingmakes the class respect the running user's record access. Choose the sharing keyword deliberately for every handler. A class without a keyword inherits the sharing mode of its caller, and a trigger runs in system mode by default.
Where the batch boundary hides
Bulk bugs rarely sit in the trigger. They appear when a handler method that looked fine for one record is reused by another method.
Compare these two helpers:
public with sharing class AccountHelper {
// Not bulk-safe: one query each time it is called.
public static String getIndustry(Id accountId) {
return [SELECT Industry FROM Account WHERE Id = :accountId].Industry;
}
// Bulk-safe: one query for any number of accounts.
public static Map<Id, String> getIndustries(Set<Id> accountIds) {
Map<Id, String> result = new Map<Id, String>();
for (Account a : [
SELECT Id, Industry FROM Account WHERE Id IN :accountIds
]) {
result.put(a.Id, a.Industry);
}
return result;
}
}Calling getIndustry inside a loop over 200 contacts runs 200 queries and fails at the 101st. The signature itself gives it away. A parameter that is a single Id or a single SObject is a warning sign. Design helper methods to take Set<Id>, List<SObject> or Map parameters so the safe path is the only path.
Order of execution and why before and after differ
Choosing between before and after triggers also affects limits.
- Before triggers fire before the record is saved. You can change
Trigger.newfields without any DML, so field defaults and derived values belong here. - After triggers fire once the record has an Id. Use them for work that needs that Id, such as creating child records, or for changes to other objects.
Putting field updates on the triggering record in an after trigger forces you to run an extra update on records that you already hold. That second update also fires the object's triggers again, so one change becomes two trips through the trigger. The next chapters on limits and recursion show why that matters.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `Too many SOQL queries: 101` | A handler method that takes one record is called in a loop | Change the method to accept a collection |
| `NullPointerException` in before insert | Code uses `Trigger.newMap` before records have Ids | Use `Trigger.new` in before insert |
| `Record is read-only` in an after trigger | A field on a `Trigger.new` record was assigned | Query or construct a new record and update it, or move the logic to a before trigger |
| Logic runs twice | An `update` inside the trigger fires the same trigger again | Move the change to a before trigger, or see the recursion chapter |
| Business rule works in the UI but fails in a data load | Code was written and tested for one record | Test with 200 records, as described in the testing chapter |
Choosing a handler design
A static handler like the one above is enough for most orgs. Larger code bases sometimes use an instance-based handler, a base class with one overridable method per event, or a trigger framework. Weigh them on these points:
- Static methods are the simplest and are easy to read. They are harder to replace with a stub in tests.
- Instance handlers allow constructor injection and inheritance. They add boilerplate that small objects do not need.
- A framework gives you a consistent pattern across many objects and can add features such as a bypass switch. It is also one more thing for the team to learn and maintain.
Whichever you choose, the bulk rules stay the same: collections in, one query, one DML statement.
Exercise
A teammate writes this inside ContactTriggerHandler.afterUpdate: for (Contact c : newContacts) { Account a = AccountHelper.getAccount(c.AccountId); ... }, where getAccount runs a single SOQL query. What goes wrong when 150 contacts are updated in one transaction, and how would you restructure the code?
Show answer
The helper runs one query per contact, so 150 contacts use 150 SOQL queries and the transaction fails with Too many SOQL queries: 101. Restructure by collecting the AccountId values into a Set<Id> before the loop, adding a helper such as getAccounts(Set<Id>) that runs one query and returns a Map<Id, Account>, and then looking up each contact's account with map.get(c.AccountId) inside the loop. Check for null for contacts with no account.
Exercise
Why is it a problem to call update newContacts; at the end of a before update handler method, and what should you do instead?
Show answer
The records in Trigger.new are already being saved, so explicit DML on them in a before trigger is not allowed and raises an error. In a before trigger, assign the new field values directly on the records in Trigger.new, and Salesforce saves them as part of the original operation.