Concept 9 of 10Triggers and testing

Trigger frameworks

One trigger per object, logic in handler classes, bypass switches, recursion control, and metadata-driven frameworks that order actions and let Flow and Apex coexist.

Your confidence:Not rated

Simple explanation

A trigger framework is a convention plus a small amount of shared code that keeps triggers predictable.

The rules

  1. One trigger per object, covering all events. Several triggers on one object run in an undefined order.
  2. No logic in the trigger. The trigger calls a dispatcher; logic lives in handler or action classes.
  3. One method per event (before insert, after update…), each bulk-safe.
  4. Bypass switches to turn off automation for data loads or specific users, from custom metadata, custom settings or a custom permission.
  5. Recursion control that prevents re-processing the same records for the same event, not a blunt static boolean that blocks legitimate second updates.

Two common styles

  • Handler class per object (a virtual base class with beforeInsert, afterUpdate… methods). Simple and widely understood.
  • Metadata-driven frameworks (for example the open-source Trigger Actions Framework): each action is a small class or a Flow, registered in custom metadata with an order and a bypass flag. Admins can see and reorder automation, and Apex and Flow actions run in one defined sequence.

Real-world analogy

A trigger framework is a switchboard operator. Every call (record event) comes into one switchboard (one trigger per object). The operator connects it to the right extensions (handlers) in a fixed order, and can put lines on hold (bypass) during maintenance.

Worked example

A minimal, production-style handler framework:

// Trigger: one per object, no logic.
trigger OpportunityTrigger on Opportunity (
    before insert, before update, after insert, after update, after delete, after undelete
) {
    new OpportunityTriggerHandler().run();
}
public virtual class TriggerHandler {
    private static Set<String> bypassed = new Set<String>();
    // Records already processed per handler + event, to stop true recursion only.
    private static Map<String, Set<Id>> processed = new Map<String, Set<Id>>();

    public void run() {
        String name = String.valueOf(this).substringBefore(':');
        if (bypassed.contains(name) || FeatureSwitch.isBypassed(name)) {
            return;
        }
        switch on Trigger.operationType {
            when BEFORE_INSERT { beforeInsert(); }
            when BEFORE_UPDATE { beforeUpdate(); }
            when AFTER_INSERT  { afterInsert(); }
            when AFTER_UPDATE  { afterUpdate(); }
            when AFTER_DELETE  { afterDelete(); }
            when AFTER_UNDELETE { afterUndelete(); }
            when else { }
        }
    }

    /** Returns only the records this handler hasn't processed yet for the current event. */
    protected List<SObject> unprocessed(List<SObject> records) {
        String key = String.valueOf(this).substringBefore(':') + '|' + Trigger.operationType;
        Set<Id> done = processed.containsKey(key) ? processed.get(key) : new Set<Id>();
        List<SObject> fresh = new List<SObject>();
        for (SObject r : records) {
            if (r.Id == null || !done.contains(r.Id)) {
                fresh.add(r);
                if (r.Id != null) { done.add(r.Id); }
            }
        }
        processed.put(key, done);
        return fresh;
    }

    public static void bypass(String handlerName) { bypassed.add(handlerName); }
    public static void clearBypass(String handlerName) { bypassed.remove(handlerName); }

    protected virtual void beforeInsert() {}
    protected virtual void beforeUpdate() {}
    protected virtual void afterInsert() {}
    protected virtual void afterUpdate() {}
    protected virtual void afterDelete() {}
    protected virtual void afterUndelete() {}
}
public with sharing class OpportunityTriggerHandler extends TriggerHandler {
    protected override void afterUpdate() {
        List<Opportunity> changed = (List<Opportunity>) unprocessed(Trigger.new);
        OpportunityAfterUpdateHandler.handle(changed, (Map<Id, Opportunity>) Trigger.oldMap);
    }
}

FeatureSwitch.isBypassed reads a custom metadata record or a custom permission, so a data-load user can bypass automation without a deployment.

Diagram

Rendering diagram…

Key points

  • One trigger per object, no logic in it; a dispatcher calls handlers or actions.
  • Handlers are bulk-safe and delegate to services.
  • Bypass via custom metadata, custom settings or custom permissions, for data loads and integrations.
  • Recursion control by record and event, not a single static boolean.
  • Metadata-driven frameworks order Apex and Flow actions and make automation visible.
  • Decide where Flow ends and Apex begins, per object, and document it.

Limits and gotchas

  • A static hasRun boolean stops legitimate second updates in the same transaction (for example a workflow field update or a second DML on different fields). Track processed record IDs per event instead.
  • Bypass switches must be audited: who bypassed what and when. Don't leave them on after a load.
  • Record-triggered flows and Apex triggers both run on the same save. Without an agreed order, behaviour is hard to predict. A metadata-driven framework, or clear before/after ownership, solves this.
  • Trigger code must handle delete and undelete, where Trigger.new or Trigger.old is null.

🎀 How to say this in an interview

"Describe your trigger framework" is near-certain in a technical round. Cover the five rules, show the bypass and recursion approach, and say how Flow and Apex coexist on the same object. Mention that you'd adopt an established open-source framework rather than invent one.

Common follow-ups

Why is a static boolean a poor recursion guard?

It blocks all re-entry for the rest of the transaction, including legitimate updates such as a second DML on different records or a workflow field update that should re-run logic. Tracking processed record IDs per event (or comparing old and new values) is precise.

How do you let admins use Flow without fighting the Apex triggers?

Agree ownership per object (for example before-save field defaults in Flow, complex logic in Apex), or use a metadata-driven framework where Flow actions are registered alongside Apex actions with an explicit order and bypass.