Sub topic 4
The one-trigger-per-object rule
This chapter assumes you can read and write basic Apex (classes, methods, collections). It also assumes you know the DML operations and the trigger events, and that you know the governor limits apply to a whole transaction. The chapter defines the rule, explains the reasons for it, and shows how to apply it to an org that already has several triggers on one object. Handler classes and dispatching get their own chapters.
The rule
An object should have exactly one Apex trigger. That trigger subscribes to every event the object can raise, and it contains no business logic. It passes control to a class that does the work.
The rule is a convention, and the platform does not enforce it. Salesforce lets you create as many triggers on an object as you like. The convention exists because of what the platform does not promise when you do.
What goes wrong with several triggers
Execution order is not guaranteed
If two triggers on the same object subscribe to the same event, for example before insert, both run. Salesforce does not define which runs first. The order can differ between orgs, between deployments, and sometimes between transactions. Salesforce documents this explicitly.
A pair of triggers on Account shows the problem:
trigger AccountDefaults on Account (before insert) {
for (Account acc : Trigger.new) {
acc.Description = 'Created without a description';
}
}trigger AccountNaming on Account (before insert) {
for (Account acc : Trigger.new) {
acc.Description = 'Imported: ' + acc.Name;
}
}Both triggers write Description. Whichever runs last wins. A test that passes in a sandbox can fail in production if the order flips, and the failure will not point at either trigger.
Logic is scattered
With several triggers, nobody can answer "what happens when an Account is inserted?" by opening one file. A developer has to search the org for every trigger on the object and read each one. Changes made to one trigger can break assumptions in another, and the code review of a single trigger never shows the whole picture.
Limits are shared
Every trigger on an object runs in the same transaction. They share one set of governor limits: 100 SOQL queries and 150 DML statements for synchronous Apex, plus CPU time and heap. If each of three triggers runs one query per record, the queries add up. With several independent triggers, no single place can see or control the total.
Shared state is hard to manage
Controlling recursion, skipping logic during a data load, or passing data from one step to the next needs shared state. Separate triggers have no natural place to hold it. A single entry point does.
The table summarizes the difference.
| Concern | Several triggers | One trigger plus handler |
|---|---|---|
| Order of logic on one event | Undefined between triggers | You decide, in code order |
| Finding the logic | Search the whole org | Open one trigger and one handler |
| Governor limit use | Spread out, hard to audit | Visible in one call path |
| Recursion and bypass control | No shared place | One static control point |
| Testing | Behavior depends on order | One deterministic path |
What the rule gives you
With one trigger, ordering becomes a matter of code. Inside the handler, you call method A and then method B, and that sequence is the same every time. You can read it, review it, and test it.
The diagram contrasts the two layouts.
Writing the single trigger
Name the trigger after the object, such as AccountTrigger. For a custom object Invoice__c, use InvoiceTrigger. Subscribe to all seven events so that future logic never needs a second trigger:
trigger AccountTrigger on Account (
before insert, before update, before delete,
after insert, after update, after delete, after undelete
) {
new AccountTriggerHandler().run();
}The body is one line. It creates a handler and calls run(). There are no loops, no queries, no if statements.
For the trigger to compile, AccountTriggerHandler must exist. Here is a minimal version that does nothing yet:
public with sharing class AccountTriggerHandler {
public void run() {
// Dispatching by operation type is covered in a later chapter.
}
}Why subscribe to every event
Subscribing to events you do not use costs almost nothing. The handler simply does nothing for those events. Subscribing to all of them has a real benefit. When someone later needs after delete logic, they add a method to the handler. They do not create a second trigger, which is how the multiple-trigger problem starts.
The alternative is to subscribe only to the events you use today and edit the trigger when a new event is needed. That also follows the rule, but it means changing the trigger file each time, and trigger changes go through deployment like any other change. Most teams prefer the all-events approach because the trigger file is then written once and never touched again.
Why no logic in the trigger
Triggers are hard to test in isolation and cannot be reused, because you cannot call a trigger from another class. They also cannot hold methods, static variables used as guards, or constants. A class can do all of these. Keeping the trigger as a one-line router moves everything useful into a place where Apex's normal tools work.
Applying the rule to an existing org
Most orgs adopt this rule after the fact. A safe consolidation follows these steps:
- List every trigger on the object. In the Developer Console, or with a SOQL query on
ApexTriggerthrough the Tooling API, filter byTableEnumOrId. - For each trigger, note its events and what its logic does. Pay attention to fields that more than one trigger writes. Those are the cases where order currently matters.
- Decide the intended order and write it down. If two triggers write the same field today, find out which result the business actually relies on.
- Move each trigger's logic into a method in the handler, one method per event. Call the methods in the order you decided.
- Write tests that insert, update, and delete 200 records and check the results, before and after the change. Tests that pass on the old triggers and on the new handler show that the behavior is preserved.
- Replace the old triggers with the single trigger. In production you cannot delete a trigger through the UI. Deploy a destructive change, or deploy the old triggers with status
Inactivefirst.
An inactive trigger is set in the trigger's metadata file:
<?xml version="1.0" encoding="UTF-8"?>
<ApexTrigger xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>61.0</apiVersion>
<status>Inactive</status>
</ApexTrigger>Edge cases
Triggers you do not own
Managed packages can ship their own triggers on standard objects such as Account or Contact. You cannot edit those, and you cannot consolidate them with yours. Your single trigger still runs in the same transaction, and the order between your trigger and the package trigger is still undefined. Design your handler so it does not depend on running before or after a package trigger.
Other automation on the same object
Triggers are one part of the order of execution. Record-triggered flows, validation rules, workflow rules, and assignment rules also run around them. One trigger gives you order inside the Apex step. It does not change when the Apex step happens relative to flows. If a flow updates the record and causes the trigger to fire again, that is a recursion case, handled in a later chapter.
Separate triggers for separate teams
Some organizations split triggers by team or by feature, so that teams do not edit the same file. This trades merge conflicts for undefined order. A better way to keep teams apart is one trigger and one handler per object, where the handler calls separate classes for each team's feature in a defined order. The handler stays a thin router, and the teams edit their own classes.
Generated or framework triggers
Some frameworks generate triggers, and some tools expect a trigger per feature. If you adopt one, keep the invariant that matters: one entry point per object. Check how the framework dispatches before you rely on it.
Common errors
- Creating a second trigger "just for this one change" because the first one looks off-limits. Add a method to the handler instead.
- Subscribing the trigger to only some events and then adding another trigger for a missing one.
- Leaving old triggers active after copying their logic into the handler. The logic then runs twice.
- Putting a
forloop or a query in the trigger body "because it is short". It will grow. - Naming triggers inconsistently, so the second trigger on an object is hard to find. Use
ObjectNameTriggereverywhere.
Exercise
An org has two active triggers on Contact, both on before update. Trigger A sets Contact.Title to a default when it is blank. Trigger B trims Contact.Title. After a deployment, some records end up with a title that has trailing spaces. What is the likely cause, and how does the one-trigger-per-object rule fix it?
Show answer
Salesforce does not guarantee the order of triggers on the same object and event. After the deployment, trigger A can run after trigger B, so the default value is set after the trim and keeps its trailing spaces. With one ContactTrigger that calls a handler, the handler sets the default first and trims second, in code. The order is the same on every run, and a test can check it.
Exercise
Why does the single trigger subscribe to all seven events even when the handler only uses before insert today?
Show answer
The handler ignores events it does not handle, so the extra subscriptions cost almost nothing. When after delete logic is needed later, a developer adds a method to the handler and does not create a second trigger. That keeps the object at one trigger and avoids editing the trigger file.