Sub topic 3
Structuring Bulk-Safe Triggers and Handlers
Assume you know Apex classes, collections, SOQL, DML, and trigger events. A bulk-safe trigger treats Trigger.new and Trigger.old as collections, because one transaction can contain up to 200 records.
Keep Triggers Thin
Put orchestration in a handler class. Gather IDs, query related records once, and perform DML after the loop.
trigger AccountAfter on Account (after insert) {
AccountHandler.afterInsert(Trigger.new);
}
public class AccountHandler {
public static void afterInsert(List<Account> accounts) {
List<Task> tasks = new List<Task>();
for (Account account : accounts) {
tasks.add(new Task(
WhatId = account.Id,
Subject = 'Follow up'
));
}
if (!tasks.isEmpty()) {
insert tasks;
}
}
}Checking Consumption with the Limits Class
Use Limits while diagnosing resource usage. The first method reports consumption; the second reports the transaction maximum.
System.debug('Queries: ' + Limits.getQueries() + '/' + Limits.getLimitQueries());
System.debug('DML: ' + Limits.getDmlStatements() + '/' + Limits.getLimitDmlStatements());
System.debug('CPU: ' + Limits.getCpuTime() + '/' + Limits.getLimitCpuTime());
System.debug('Heap: ' + Limits.getHeapSize() + '/' + Limits.getLimitHeapSize());Testing with 200 Records
A test should send a full batch through the trigger. This exposes queries or DML statements hidden inside loops.
@IsTest
private class AccountAfterTest {
@IsTest
static void handlesFullBatch() {
List<Account> accounts = new List<Account>();
for (Integer i = 0; i < 200; i++) {
accounts.add(new Account(Name = 'Test ' + i));
}
Test.startTest();
insert accounts;
Test.stopTest();
System.assertEquals(200,
[SELECT COUNT() FROM Task WHERE Subject = 'Follow up']);
}
}CPU Time and Heap Size
CPU time measures processing work. Heap size measures memory used by objects and collections. Large nested loops, repeated calculations, and unnecessarily large query results can exhaust either limit. Query only needed fields and avoid retaining unused records.
Moving Heavy Work Asynchronously
Queueable Apex is useful for one job with parameters and complex processing. Batch Apex is better for very large data sets because each batch execution receives fresh limits.
public class RecalculateAccounts implements Queueable {
private Set<Id> accountIds;
public RecalculateAccounts(Set<Id> accountIds) {
this.accountIds = accountIds;
}
public void execute(QueueableContext context) {
List<Account> accounts = [
SELECT Id, Description FROM Account WHERE Id IN :accountIds
];
update accounts;
}
}
// System.enqueueJob(new RecalculateAccounts(accountIds));Preventing Trigger Recursion
A trigger can update records that cause itself to run again. Use static state to limit repeated work during one transaction.
public class TriggerState {
public static Set<Id> processedAccountIds = new Set<Id>();
}Before processing an account, skip IDs already in this set and add new IDs as they are accepted. Choose a Set<Id> when each record should run once; a Boolean is simpler only when the whole handler should run once.
Exercise
Why should a trigger test insert 200 records instead of one?
Show answer
A full batch reveals per-record SOQL or DML that may exceed transaction limits.