Sub topic 2
Keeping the Apex Trigger Body Logic-Less
Assume you know basic Apex classes, collections, DML operations, and Salesforce governor limits. This chapter focuses on organizing trigger code so it remains predictable as requirements grow.
Keep the Trigger Logic-Less
A trigger should declare when it runs and delegate immediately. If several triggers exist for one object, Salesforce does not provide a reliable order for them. Their behavior can become difficult to trace when they update the same records or depend on each other.
Use one trigger per object. Keep business decisions in a handler class.
trigger AccountTrigger on Account (
before insert, before update, before delete,
after insert, after update, after delete, after undelete
) {
new AccountTriggerHandler().run();
}Move Work into a Handler
The handler receives the trigger context and chooses the method for the current operation. Trigger.operationType identifies both the timing and DML operation, such as BEFORE_INSERT or AFTER_UPDATE.
public with sharing class AccountTriggerHandler {
public void run() {
switch on Trigger.operationType {
when BEFORE_INSERT {
beforeInsert((List<Account>) Trigger.new);
}
when BEFORE_UPDATE {
beforeUpdate(
(List<Account>) Trigger.new,
(Map<Id, Account>) Trigger.oldMap
);
}
when AFTER_INSERT {
afterInsert((List<Account>) Trigger.new);
}
when else {
// No behavior is needed yet.
}
}
}
private void beforeInsert(List<Account> accounts) {
for (Account account : accounts) {
if (String.isBlank(account.Description)) {
account.Description = 'Created without a description';
}
}
}
private void beforeUpdate(
List<Account> accounts,
Map<Id, Account> oldAccounts
) {
for (Account account : accounts) {
if (account.Name != oldAccounts.get(account.Id).Name) {
account.Description =
'Renamed from ' + oldAccounts.get(account.Id).Name;
}
}
}
private void afterInsert(List<Account> accounts) {
List<Task> followUps = new List<Task>();
for (Account account : accounts) {
followUps.add(new Task(
WhatId = account.Id,
Subject = 'Welcome call'
));
}
insert followUps;
}
}Dispatch and Bulkify
Trigger.new and Trigger.oldMap contain the records in the current transaction. Salesforce can send up to 200 records to one trigger invocation. Therefore, handler methods must process collections.
The example performs one loop to prepare tasks and one DML statement after the loop. Do not query or perform DML once per record.
Exercise
Why does afterInsert build a Task list before inserting it?
Show answer
It keeps the method bulk-safe by using one DML statement for the whole trigger batch instead of one statement per Account.