Skip to content
StackDecode
IntermediateLesson 20 of 37

Trigger best practices

Bulkify, one trigger per object, logic in handlers.

  • One trigger per object, delegating to a handler class.
  • Bulkification: loops over Trigger.new; collect Ids, query once, update a list once.
  • Avoid recursion with a static flag, or design updates so they do not re-fire.
  • Prefer Flow for simple automation; use triggers for complex logic.
apex
trigger AccountTrigger on Account (before insert, before update) {
    AccountTriggerHandler.run(Trigger.new, Trigger.oldMap, Trigger.operationType);
}
apex
public with sharing class AccountTriggerHandler {
    public static void run(List<Account> news, Map<Id, Account> oldMap, System.TriggerOperation op) {
        Set<Id> parentIds = new Set<Id>();
        for (Account a : news) { if (a.ParentId != null) parentIds.add(a.ParentId); }
        Map<Id, Account> parents = new Map<Id, Account>([SELECT Id, Industry FROM Account WHERE Id IN :parentIds]);
        for (Account a : news) {
            if (a.Industry == null && parents.containsKey(a.ParentId)) {
                a.Industry = parents.get(a.ParentId).Industry;
            }
        }
    }
}