Sub topic 1
The Trigger Handler Pattern: One Trigger per Object in Apex
Prerequisites
Assume you know basic Apex classes, methods, and collections. You should also understand Salesforce records, DML operations such as insert and update, and governor limits.
What an Apex Trigger Is and When It Fires
An Apex trigger is code that Salesforce runs automatically when records change. A trigger can run before or after an operation. Common operations are insert, update, delete, and undelete.
Use a before trigger to change field values on records before Salesforce saves them. Use an after trigger when you need saved record IDs or want to create related records.
trigger AccountTrigger on Account (
before insert, before update, before delete,
after insert, after update, after delete, after undelete
) {
new AccountTriggerHandler().run();
}The trigger above subscribes to every common Account event. It delegates the work to a handler instead of containing business logic.
Reading Trigger Context Variables
Trigger context variables describe the records and operation. Trigger.new contains the incoming record versions. Trigger.oldMap maps each existing record ID to its previous version. Trigger.operationType identifies the current event, such as BEFORE_INSERT or AFTER_UPDATE.
Some variables are available only for certain events:
| Variable | Typical use | Available in |
|---|---|---|
| `Trigger.new` | Read or change incoming records | Insert and update |
| `Trigger.oldMap` | Compare old and new values | Update and delete |
| `Trigger.operationType` | Select the correct method | All trigger events |
For example, an update handler can compare Trigger.new with Trigger.oldMap to detect changed fields.
Why Several Triggers on One Object Cause Trouble
Salesforce does not provide a reliable execution order for multiple triggers on the same object and event. If two Account triggers both update records, their order can change the result. Each trigger may also perform queries or DML, consuming the same transaction limits.
This makes behavior difficult to predict, test, and extend.
flowchart TD
A[Account DML] --> B[One trigger entry point]
B --> C[Handler dispatch]
C --> D[Event-specific method]The One-Trigger-per-Object Rule
Use one trigger for each object. Let that trigger route execution to a handler class. The handler can then dispatch by Trigger.operationType, centralize ordering, and keep each operation bulk-safe.
Exercise
Which context variable should an update handler use to compare a record's current and previous Name?
Show answer
Use Trigger.new for the current record and Trigger.oldMap for the previous record.