Snippet Apex 24 Apr 2026

Bulk-safe trigger handler skeleton

The five-method handler shape that survives 200-record batches — collect, query once, map, loop, DML once.

public with sharing class AccountTriggerHandler {
    public static Boolean bypass = false;

    public static void beforeInsert(List<Account> records) {
        if (bypass) return;
        for (Account acc : records) {
            // never SOQL/DML inside this loop
            acc.Rating = acc.AnnualRevenue > 1000000 ? 'Hot' : 'Warm';
        }
    }

    public static void afterUpdate(Map<Id, Account> oldMap,
                                   Map<Id, Account> newMap) {
        List<Account> changed = new List<Account>();
        for (Account acc : newMap.values()) {
            if (acc.OwnerId != oldMap.get(acc.Id).OwnerId) {
                changed.add(acc);
            }
        }
        if (!changed.isEmpty()) OwnerSync.enqueue(changed);
    }
}

The five-method handler shape that survives 200-record batches — collect, query once, map, loop, DML once.

Gotchas

The bypass flag is for data migrations and tests only — every production use deserves a code comment explaining itself. And afterUpdate compares old to new before doing anything: change detection is what keeps recursion away.