Sub topic 5
Keeping the trigger body logic-less
This chapter assumes you can read basic Apex (classes, methods, collections), know what DML operations are, and have seen governor limits mentioned. The earlier chapters covered when triggers fire and why one trigger per object is the rule. This chapter covers what the one trigger should contain: almost nothing.
What "logic-less" means
A logic-less trigger declares which events it listens to and then hands control to a class. It has no if statements, loops, queries, or DML of its own. All decisions live in the handler class.
trigger AccountTrigger on Account (
before insert, before update, before delete,
after insert, after update, after delete, after undelete
) {
new AccountTriggerHandler().run();
}The trigger has three parts:
- The name.
AccountTriggerfollows the<Object>Triggerconvention, so anyone can find the single trigger for an object. - The event list. It subscribes to all seven events, so the platform always calls the trigger.
- The delegation line. It creates the handler and calls
run(). The handler decides what happens next.
Why the trigger body is a poor place for logic
A trigger is a special kind of metadata, not an ordinary class. That limits what you can do with code written inside it.
- It can't be called from elsewhere. A trigger runs only when the platform fires it. You can't reuse its code from a batch job, a controller, or a test helper.
- It can't hold static state. Triggers can't declare static variables. Patterns such as a recursion guard need a class to store that state.
- It can't be extended. A trigger has no inheritance, so you can't share dispatch code across objects. A base class can, as a later chapter shows.
- It is hard to test in isolation. The only way to run trigger code is to perform DML on the object. Logic in a class can also be tested through DML, but a class lets you add focused unit tests for individual methods.
- It grows without limits. A trigger with two screens of nested conditions is hard to review, and each change risks breaking an unrelated branch.
Moving the logic into a class removes these restrictions. The trigger becomes a fixed entry point that you rarely edit again.
A before and after comparison
Here is a typical trigger that mixes concerns. It contains logic that works for one record and fails for a bulk load.
trigger AccountTrigger on Account (before insert, after insert) {
if (Trigger.isBefore) {
for (Account acc : Trigger.new) {
if (String.isBlank(acc.Description)) {
acc.Description = 'Created without a description';
}
}
}
if (Trigger.isAfter) {
for (Account acc : Trigger.new) {
// Bad: one query per record.
User owner = [SELECT Id, Email FROM User WHERE Id = :acc.OwnerId];
// Bad: one DML statement per record.
insert new Task(WhatId = acc.Id, OwnerId = owner.Id, Subject = 'Welcome call');
}
}
}Inserting 200 accounts in one operation runs 200 queries, which is over the limit of 100 SOQL queries per synchronous transaction. The same code also issues 200 DML statements, which is over the limit of 150. The trigger fails with a governor limit exception.
The fix has two parts. First, the trigger becomes the three-line version shown earlier. Second, the logic moves into the handler and is written to be bulk-safe. A later chapter covers bulk safety in detail. Here is the afterInsert method in the handler:
private void afterInsert(List<Account> newAccounts) {
List<Task> followUps = new List<Task>();
for (Account acc : newAccounts) {
followUps.add(new Task(
WhatId = acc.Id,
OwnerId = acc.OwnerId,
Subject = 'Welcome call'
));
}
insert followUps; // one DML statement for the whole batch
}The trigger no longer needs to change when this logic does. A reviewer can read the handler method on its own, and a test can cover it through ordinary DML.
What belongs where
| Concern | Trigger | Handler class |
|---|---|---|
| Object and event list | Yes | No |
| Creating the handler and calling `run()` | Yes | No |
| Checking `Trigger.operationType` | No | Yes |
| Casting `Trigger.new` and `Trigger.oldMap` | No | Yes |
| Field defaults and validation | No | Yes |
| SOQL and DML | No | Yes |
| Static state such as a recursion guard | Not allowed | Yes |
If you are unsure where a line of code goes, ask whether it describes how the platform connects to your code or what your code does. Connection code stays in the trigger. Everything else goes in the class.
How a save reaches your code
The trigger has no branches. All branching starts at the handler's run() method. A later chapter covers the dispatch step. A handler can also stay thin by passing the real work to service classes, which keeps business rules reusable outside the trigger.
Event subscription: all events or only the ones you need
The example trigger subscribes to all seven events even though the handler only acts on three of them. This choice has a trade-off.
- Subscribe to everything. Adding handling for a new event later means changing only the handler. The trigger file stays the same, so you don't redeploy it. The cost is that the platform invokes the trigger and creates a handler object for events you ignore. That cost is small.
- Subscribe to only what you use. The event list documents what the object actually reacts to. Adding a new event means editing the trigger as well as the handler.
This tutorial uses the first approach because the handler's when else branch already makes unhandled events harmless. If your team prefers explicit event lists, the pattern works the same way. The point is that either choice still leaves the trigger body with no logic.
Deployment files
A trigger deploys as two files, which is another reason to keep it small. Here is the metadata file that sits next to AccountTrigger.trigger:
<?xml version="1.0" encoding="UTF-8"?>
<ApexTrigger xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>62.0</apiVersion>
<status>Active</status>
</ApexTrigger>The status field controls whether the trigger runs. Setting it to Inactive is a way to switch off the trigger in a sandbox. In production you can't deploy a trigger that has no test coverage, so the handler needs tests regardless. The testing chapter covers this.
Common errors
- Putting "just one small check" in the trigger. The check grows, and then someone adds a query beside it. Keep the rule strict: no logic at all.
- Creating a second trigger for a new feature. Add a method to the handler instead. A second trigger on the same object has no guaranteed execution order relative to the first.
- Forgetting an event in the list. If
after updateisn't in the trigger's event list, the handler'safterUpdatemethod never runs, and nothing reports an error. When a handler branch seems to be ignored, check the trigger's event list first. - Naming the handler after the feature rather than the object. A name like
WelcomeCallHandlermakes it unclear which trigger calls it.AccountTriggerHandlermatchesAccountTrigger. - Passing context variables into the handler's constructor.
Trigger.newand the other context variables are available inside any class that runs in trigger context, so the trigger doesn't need to pass them. Reading them inside the handler keeps the trigger body to one line.
Summary of the rule
The trigger declares events and makes one call. The handler holds the logic. Because the trigger never changes, every future feature is a handler change that you can review and test as ordinary class code.
Exercise
A teammate adds this to AccountTrigger: if (Trigger.isAfter && Trigger.isUpdate) { AccountService.syncToBilling(Trigger.new); }. Name two problems with this change and describe how to fix it.
Show answer
First, the trigger now contains branching logic, which breaks the logic-less rule and makes the trigger harder to review and test. Second, the call is not covered by the handler's dispatch, so the handler and the trigger now each decide what happens on after update, and the two can disagree. To fix it, remove the if from the trigger so that its body is only new AccountTriggerHandler().run();. Then add an afterUpdate method to the handler that calls AccountService.syncToBilling, and add AFTER_UPDATE to the switch on Trigger.operationType block. Check that after update is in the trigger's event list.
Exercise
Your handler has an afterUpdate method, but it never runs when you update an Account in a test. The handler's dispatch includes when AFTER_UPDATE. What do you check first, and why?
Show answer
Check the event list on the trigger declaration. If it lists only before insert, after insert, the platform never calls the trigger for updates, so the handler is never created and its dispatch never runs. Add after update to the list and run the test again.