Sub topic 2
Static Variables Live for One Transaction
Prerequisites: you should know basic Apex collections, triggers, DML, and Salesforce governor limits.
A static variable belongs to the Apex class, not to a particular object record. Its value remains available while the current transaction runs. If a trigger fires again during that transaction, the trigger can see the same static value. When the transaction ends, Salesforce clears the value.
This makes static variables useful for detecting re-entry. Re-entry happens when trigger logic performs DML that causes the same trigger to run again.
The Static Boolean Flag Guard
A static Boolean is a true-or-false flag. The first invocation sets it to true. A later invocation returns immediately.
public class AccountTriggerHandler {
private static Boolean hasRun = false;
public static void afterUpdate(List<Account> newList) {
if (hasRun) {
return;
}
hasRun = true;
List<Account> updates = new List<Account>();
for (Account acc : newList) {
updates.add(new Account(
Id = acc.Id,
Description = 'Reviewed'
));
}
if (!updates.isEmpty()) {
update updates;
}
}
}The guard prevents the second invocation from issuing another update. This stops an otherwise repeating cycle. Keep the guard in a handler class so the trigger stays small and the state is easier to test.
Why a Boolean Can Skip Records Beyond 200
Salesforce processes large DML operations in chunks of up to 200 records. Suppose one update contains 400 Accounts:
- The first chunk enters the handler and sets
hasRuntotrue. - The first chunk is processed.
- The second chunk enters the same transaction.
- The Boolean is still
true, so the handler returns. - The second chunk is skipped.
Therefore, a Boolean guard is safe only when later chunks must not be processed, or when the operation is known to contain one relevant chunk. For bulk-safe logic, track processed record Ids in a static Set<Id> instead. That allows the handler to skip only records it has already handled.
Exercise
Why does a static Boolean remain true when the trigger processes a second 200-record chunk?
Show answer
Both chunks run in the same transaction, and static variables keep their values until that transaction ends.