Sub topic 11
Handlers as Thin Routers over Service Classes
This chapter assumes you can write basic Apex classes and methods, and that you already have a logic-less trigger that calls an AccountTriggerHandler. It also assumes you know the DML operations and the governor limits. Here you will decide what belongs in the handler and what belongs in a service class.
The problem with a fat handler
A handler is easy to start with. You add a few lines to beforeInsert, then a few more to afterInsert. After a year the handler holds validation rules, defaulting logic, task creation and callouts to other objects. It is no longer a router. It is a second place where all the logic is tangled together.
A fat handler causes three problems:
- Reuse is hard. A Lightning controller, a batch job or a REST endpoint may need the same rule. Calling a handler from outside a trigger is awkward because the handler reads
Trigger.new. - Tests are slow. To test one rule you must run DML and fire the whole trigger.
- Reading is hard. The dispatch code and the business rules sit in the same methods.
The split
Give each class one job:
| Layer | Job | Knows about triggers? |
|---|---|---|
| Trigger | Subscribes to events and calls the handler | Yes |
| Handler | Reads the context and routes records to the right service method | Yes |
| Service class | Holds the business rules and takes plain collections | No |
The handler keeps the Trigger references. The service class receives lists and maps, so any caller can use it.
Example
This service class holds the welcome-task rule from the earlier afterInsert method. It takes a List<Account> and has no reference to Trigger.
public with sharing class AccountService {
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'));
}
insert followUps; // one DML statement for the whole batch
}
public static void setDefaultDescription(List<Account> accounts) {
for (Account acc : accounts) {
if (String.isBlank(acc.Description)) {
acc.Description = 'Created without a description';
}
}
}
}The handler now only routes:
public with sharing class AccountTriggerHandler {
public void run() {
switch on Trigger.operationType {
when BEFORE_INSERT {
AccountService.setDefaultDescription((List<Account>) Trigger.new);
}
when AFTER_INSERT {
AccountService.createWelcomeTasks((List<Account>) Trigger.new);
}
when else {
// Other operations are not handled yet.
}
}
}
}The handler is now short enough to read in one glance. Adding a rule means adding a service method and one line in the handler.
What to watch for
The service class should not touch the Trigger variables. Once it does, you lose the reuse and the fast tests. Pass in what it needs as parameters.
Keep bulk safety in the service methods. They receive lists, so they must run one query and one DML statement for the whole list, not one per record. A controller may pass a single record, and a trigger may pass 200. The same code must handle both.
Be careful in before triggers. setDefaultDescription changes the records in the list and does not call DML. In a before trigger, the changes are saved automatically. If a service method called update on those records, it would be wrong in that context. Name and document such methods so callers know whether they save.
Sharing matters too. A service class declared with sharing respects the running user's access. If a trigger-driven rule must run in system context, make that choice on purpose and in one place.
Testing the service on its own
Because the service takes plain lists, you can test a rule without the trigger. For setDefaultDescription, build in-memory Account records and call the method. No DML runs and the test is fast. Keep one DML-based test through the handler, as in the earlier testing chapter, to prove the wiring works.
Exercise
A service method AccountService.closeStaleAccounts(List<Account> accounts) reads Trigger.newMap to find old values. What is wrong with this design, and how would you fix it?
Show answer
The service now depends on the trigger context, so a batch job or controller cannot call it and a test needs DML to fire the trigger. Fix it by having the handler read Trigger.oldMap and pass it as a second parameter, for example closeStaleAccounts(List<Account> accounts, Map<Id, Account> oldMap). The service then works with plain collections from any caller.
Exercise
Which layer should contain the switch on Trigger.operationType statement, and why?
Show answer
The handler. It is the layer that knows about triggers and routes each operation to a service method. Keeping it there leaves the service class free of Trigger references.