Sub topic 11
Handlers as Thin Routers over Service Classes
This chapter assumes you can write Apex classes and static methods. It also assumes you know the one-trigger-per-object rule, the logic-less trigger, and a handler that switches on Trigger.operationType. You should also know why handler methods must be bulk-safe. The chapter shows how to move the business rules out of the handler and into service classes.
Why the handler still grows
A handler fixes the problem of logic scattered across several triggers. It does not stop the handler from becoming the new place where everything piles up. A handler method such as afterInsert starts with one loop. Over a year it collects a query, a callout check, a task-creation block, and three special cases for one customer segment. Two problems follow:
- The logic is tied to the trigger. The handler reads
Trigger.newandTrigger.oldMap. To exercise any rule you must run DML on a real record, which makes tests slow. - The logic cannot be reused. A batch job, a Flow action, or a REST endpoint may need the same rule. Calling a trigger handler from those places does not work, because the
Triggercontext variables are empty outside a trigger.
The fix is a split of responsibilities. The handler becomes a thin router. It decides which operation is running and passes the right data to a service class. The service class holds the business rules and knows nothing about triggers.
Three layers, three jobs
| Layer | Knows about | Does | Does not do |
|---|---|---|---|
| Trigger | Events on one object | Calls the handler | Any logic |
| Handler | `Trigger.*` context, operation type | Routes, casts collections, picks which service methods run | Business rules, queries, DML |
| Service | Records and business rules | Applies rules to lists of records, runs queries and DML | Read `Trigger.*`, track recursion |
The arrows show the point of the split. The service class has several callers, and the trigger is only one of them.
Writing the service class
A good service method takes plain collections of records and returns or changes them. It does not know whether a trigger, a batch job, or a test called it. Here is a service for the Account rules from the handler in earlier chapters:
public with sharing class AccountService {
public static void setDefaultDescription(List<Account> accounts) {
for (Account acc : accounts) {
if (String.isBlank(acc.Description)) {
acc.Description = 'Created without a description';
}
}
}
public static void noteRenames(List<Account> accounts, Map<Id, Account> oldMap) {
for (Account acc : accounts) {
Account previous = oldMap.get(acc.Id);
if (previous != null && acc.Name != previous.Name) {
acc.Description = 'Renamed from ' + previous.Name;
}
}
}
public static void createWelcomeTasks(List<Account> accounts) {
List<Task> followUps = new List<Task>();
for (Account acc : accounts) {
followUps.add(new Task(WhatId = acc.Id, Subject = 'Welcome call'));
}
if (!followUps.isEmpty()) {
insert followUps; // one DML statement for the whole list
}
}
}Three design choices in this class matter.
- Every method takes a list. There is no
setDefaultDescription(Account acc). A single-record method invites a caller to loop over it, and that loop then hides a query or DML statement inside each call. A list parameter keeps the method bulk-safe. - Before-context methods change records and do no DML. In a before trigger, changes to the records in
Trigger.neware saved automatically.setDefaultDescriptionandnoteRenamesonly set field values. Callingupdateon those records inside a before trigger would be an error. - After-context methods may do DML.
createWelcomeTaskscreates related records, so it inserts them once, outside the loop. TheisEmpty()check avoids a pointless DML statement.
The handler as a router
The handler now shrinks to casting and calling. It is the only class that reads Trigger.*.
public with sharing class AccountTriggerHandler {
public void run() {
switch on Trigger.operationType {
when BEFORE_INSERT {
AccountService.setDefaultDescription((List<Account>) Trigger.new);
}
when BEFORE_UPDATE {
AccountService.noteRenames(
(List<Account>) Trigger.new,
(Map<Id, Account>) Trigger.oldMap
);
}
when AFTER_INSERT {
AccountService.createWelcomeTasks((List<Account>) Trigger.new);
}
when else {
// Other operations are not handled yet.
}
}
}
}Each when branch is one line or one short call. A reader can see from the handler alone which rules run on which event. To learn what a rule does, they open the service.
Some logic still belongs in the handler, because it depends on the trigger context:
- Choosing between
Trigger.newandTrigger.oldMapfor the event at hand. - Filtering to the records that changed, when the filter depends on old and new values from the context. A small helper in the handler can build the filtered list and pass only that list to the service.
- The recursion guard from the earlier chapter. A static set of processed Ids describes how often this trigger has fired in this transaction. The service has no reason to know that.
Reusing the service outside the trigger
Here is a class that backfills welcome tasks for existing accounts. It calls the same service method the trigger uses:
public with sharing class AccountBackfill {
public static void createMissingWelcomeTasks() {
List<Account> withoutTasks = [
SELECT Id
FROM Account
WHERE Id NOT IN (
SELECT WhatId FROM Task WHERE Subject = 'Welcome call'
)
LIMIT 200
];
AccountService.createWelcomeTasks(withoutTasks);
}
}The rule "a new account gets a welcome call task" now exists in one place. If the subject changes, you edit one line and both the trigger path and the backfill path change.
Testing services without DML
The service has no dependency on Trigger.*, so you can test most rules with records that only exist in memory. These tests run no DML, run in milliseconds, and use no org data:
@IsTest
private class AccountServiceTest {
@IsTest
static void setDefaultDescriptionFillsBlankValuesOnly() {
List<Account> accounts = new List<Account>{
new Account(Name = 'Blank'),
new Account(Name = 'Filled', Description = 'Keep me')
};
AccountService.setDefaultDescription(accounts);
Assert.areEqual('Created without a description', accounts[0].Description);
Assert.areEqual('Keep me', accounts[1].Description);
}
@IsTest
static void noteRenamesOnlyChangesRenamedAccounts() {
Id renamedId = '001000000000001';
Id sameId = '001000000000002';
List<Account> updated = new List<Account>{
new Account(Id = renamedId, Name = 'New name'),
new Account(Id = sameId, Name = 'Unchanged')
};
Map<Id, Account> oldMap = new Map<Id, Account>{
renamedId => new Account(Id = renamedId, Name = 'Old name'),
sameId => new Account(Id = sameId, Name = 'Unchanged')
};
AccountService.noteRenames(updated, oldMap);
Assert.areEqual('Renamed from Old name', updated[0].Description);
Assert.isNull(updated[1].Description);
}
}The 15-character strings are valid Id values for the Account object, because they start with the Account key prefix 001. They let you build a realistic old map without inserting anything.
You still need one DML-based test per handler, like the 200-record test from the testing chapter. That test checks the wiring: that the trigger fires, the handler routes to the right service method, and the whole path works with a full batch. The service tests check the rules in detail. Together they give you fast feedback on logic and one check that the pieces are connected.
Common mistakes
- A service that reads
Trigger.new. It works from the trigger and fails with a null reference everywhere else. It also forces every test to use DML. Pass the collections in as parameters. - A service with a recursion guard. Static guard state is about trigger re-entry, not about a business rule. Keep it in the handler. If a batch job calls the service, you do not want a stale guard to skip records.
- Services that call each other in a circle. If
AccountServicecallsContactServiceandContactServicecallsAccountService, a change in one is hard to trace and can recurse through the triggers on both objects. Keep calls going one way, or put the shared piece in a third class. - A one-record service method called in a loop. This brings back the query-in-loop and DML-in-loop problems at a distance. Take lists and return results keyed by Id if callers need per-record answers.
- Moving everything just to move it. A rule that is one line and used in one place can stay in the handler. Split a rule out when it has a second caller, when it needs its own unit tests, or when the handler method stops fitting on one screen.
Where this leaves the pattern
The pieces from the earlier chapters now have clear roles. The trigger subscribes to events. The handler turns the trigger context into typed collections and routes by operation. The service applies business rules to those collections. The recursion guard and bypass switch live around the handler, where trigger-specific concerns belong. When the next requirement arrives, you add a service method and one line to a handler branch.
Exercise
A teammate puts this method in AccountService: public static void flagLargeAccounts() { for (Account a : (List<Account>) Trigger.new) { if (a.NumberOfEmployees > 1000) a.Rating = 'Hot'; } }. Name two problems and show how to fix the signature.
Show answer
The method reads Trigger.new, so it fails with a null reference when a batch job, Flow action, or unit test calls it, and every test needs DML to run it. Fix it by taking the records as a parameter: public static void flagLargeAccounts(List<Account> accounts). The handler then calls AccountService.flagLargeAccounts((List<Account>) Trigger.new) in the before-insert and before-update branches. Because the method only sets a field value, it also needs no DML in a before context.
Exercise
You add an after-update rule that creates one Task per account whose Name changed. Which class should hold the check that compares the old and new Name, and which should hold the insert? Describe how to keep the insert bulk-safe.
Show answer
The handler can compare old and new values from Trigger.new and Trigger.oldMap and build a list of renamed accounts, since that comparison depends on the trigger context. It passes that list to a service method. The service builds a List<Task> inside its loop and runs a single insert after the loop, guarded by an isEmpty() check. The service can then also be called from a batch job with any list of accounts.