What the trigger layer has to do
Two of the acceptance criteria live here. When a referral’s Region changes (or a closed referral is reopened), it must be reassigned to the least-loaded coordinator of that region. And the bad data must be stopped at the door: no decline without a reason, no leaving New without a region.
The pattern is the same one I use everywhere: one trigger per object, no logic in it, a handler that dispatches by context, and plain service classes that do the work on whole collections.
- before insert / updateValidate, then route: stamp Assigned_Coordinator__c and Routed_On__c on the records being saved. No DML needed.
- after insert / updateSync the Share rows, which need the record Id and a DML statement of their own.
- then the FlowThe after-save Flow sees the coordinator the before trigger picked.
The trigger
trigger ReferralTrigger on Referral__c (
before insert, before update,
after insert, after update
) {
new ReferralTriggerHandler().run();
}Four lines. Everything that could go wrong (ordering, recursion, bypassing in a data load) is handled in one place instead of copied into every trigger. A second object follows the same shape: Referral_Note__c gets its own ReferralNoteTrigger and ReferralNoteTriggerHandler, and nothing is shared except the base class below.
The handler framework
public abstract inherited sharing class TriggerHandler {
private static final Set<String> bypassed = new Set<String>();
/** Switch a handler off for the rest of the transaction, e.g. during a data migration. */
public static void bypass(String handlerName) { bypassed.add(handlerName); }
public static void clearBypass(String handlerName) { bypassed.remove(handlerName); }
public void run() {
if (!Trigger.isExecuting || bypassed.contains(handlerName())) return;
switch on Trigger.operationType {
when BEFORE_INSERT { beforeInsert(Trigger.new); }
when BEFORE_UPDATE { beforeUpdate(Trigger.new, Trigger.oldMap); }
when AFTER_INSERT { afterInsert(Trigger.new); }
when AFTER_UPDATE { afterUpdate(Trigger.new, Trigger.oldMap); }
when else { /* delete and undelete are not handled yet */ }
}
}
protected virtual void beforeInsert(List<SObject> newRecords) {}
protected virtual void beforeUpdate(List<SObject> newRecords, Map<Id, SObject> oldMap) {}
protected virtual void afterInsert(List<SObject> newRecords) {}
protected virtual void afterUpdate(List<SObject> newRecords, Map<Id, SObject> oldMap) {}
private String handlerName() {
String description = String.valueOf(this);
return description.substring(0, description.indexOf(':'));
}
}The base class is inherited sharing, and each concrete handler states its own sharing mode. A handler only overrides the contexts it cares about. The bypass switch is the thing I would otherwise write badly under pressure during a data load, so it is built in from the start.
The Referral handler
It does almost nothing itself: cast, delegate, and decide which records are worth the next step.
public with sharing class ReferralTriggerHandler extends TriggerHandler {
protected override void beforeInsert(List<SObject> newRecords) {
List<Referral__c> referrals = (List<Referral__c>) newRecords;
ReferralValidator.validate(referrals, null);
ReferralRoutingService.route(referrals, null);
}
protected override void beforeUpdate(List<SObject> newRecords, Map<Id, SObject> oldMap) {
List<Referral__c> referrals = (List<Referral__c>) newRecords;
Map<Id, Referral__c> before = (Map<Id, Referral__c>) oldMap;
ReferralValidator.validate(referrals, before);
ReferralRoutingService.route(referrals, before);
}
protected override void afterInsert(List<SObject> newRecords) {
ReferralSharingService.sync((List<Referral__c>) newRecords);
}
protected override void afterUpdate(List<SObject> newRecords, Map<Id, SObject> oldMap) {
Map<Id, Referral__c> before = (Map<Id, Referral__c>) oldMap;
List<Referral__c> accessChanged = new List<Referral__c>();
for (Referral__c r : (List<Referral__c>) newRecords) {
if (ReferralChanges.affectsAccess(r, before)
&& RecursionGuard.firstVisit('referral-access', r.Id, ReferralChanges.accessState(r))) {
accessChanged.add(r);
}
}
ReferralSharingService.sync(accessChanged);
}
}Notice that nothing here loops over records to query or save. Every loop either filters a list or calls a method that takes the whole list.
Detecting what changed
Status values live in one small class, so a typo in a string literal cannot turn into a silent bug.
public inherited sharing class ReferralStatus {
public static final String NEW_REFERRAL = 'New';
public static final String TRIAGED = 'Triaged';
public static final String DECLINED = 'Declined';
public static final Set<String> CLOSED = new Set<String>{ 'Completed', 'Declined' };
public static Boolean isClosed(String status) {
return CLOSED.contains(status);
}
}A trigger fires on every update, including ones that touched an unrelated field. Comparing old and new values keeps the expensive work for the records that need it.
public inherited sharing class ReferralChanges {
/** True when the field differs from its old value. On insert (no old map) it means "has a value". */
public static Boolean changed(Referral__c r, Map<Id, Referral__c> oldMap, SObjectField field) {
Referral__c before = oldMap?.get(r.Id);
return before == null ? r.get(field) != null : r.get(field) != before.get(field);
}
/** New region, or a closed referral reopened: it needs a coordinator. */
public static Boolean needsRouting(Referral__c r, Map<Id, Referral__c> oldMap) {
if (r.Region__c == null) return false;
if (changed(r, oldMap, Referral__c.Region__c)) return true;
Referral__c before = oldMap?.get(r.Id);
return before != null
&& ReferralStatus.isClosed(before.Status__c)
&& !ReferralStatus.isClosed(r.Status__c);
}
/** Anything that changes who may see the record. */
public static Boolean affectsAccess(Referral__c r, Map<Id, Referral__c> oldMap) {
return changed(r, oldMap, Referral__c.Region__c)
|| changed(r, oldMap, Referral__c.Status__c)
|| changed(r, oldMap, Referral__c.Assigned_Coordinator__c)
|| changed(r, oldMap, Referral__c.OwnerId);
}
public static String accessState(Referral__c r) {
return String.join(new List<Object>{ r.Region__c, r.Status__c, r.Assigned_Coordinator__c, r.OwnerId }, '|');
}
}oldMap?.get(...) makes insert and update share one code path: on insert there is no old map, so a field counts as changed when it has a value. Comparing through SObjectField tokens means a renamed field is a compile error and not a silent bug.
A recursion guard that does not hide real changes
This trigger does no DML on Referral__c, but a Flow or another trigger in the same transaction can update the record and fire it again. The common fix, a static Boolean “already ran”, is wrong in a subtle way: if a later step legitimately changes the region in the same transaction, the second change is ignored.
So the guard remembers the state it already handled, not just that it ran.
public inherited sharing class RecursionGuard {
private static final Set<String> seen = new Set<String>();
/**
* True the first time this scope sees this record in this exact state, false on a repeat.
* A different state (say, the region changed again) counts as a first visit.
*/
public static Boolean firstVisit(String scope, Id recordId, String state) {
return seen.add(scope + ':' + recordId + ':' + state);
}
}Set.add returns false when the value was already there, which is the whole trick. Statics live for one transaction, so nothing leaks between requests.
The routing rule
Routing is the first thing the trigger actually decides: among the active members of the region’s coordinator group, pick the one with the fewest open referrals, and count the ones assigned in this very batch so 200 referrals spread out instead of piling onto one person.
public with sharing class ReferralRoutingService {
public static void route(List<Referral__c> referrals, Map<Id, Referral__c> oldMap) {
List<Referral__c> toRoute = new List<Referral__c>();
Set<String> regions = new Set<String>();
for (Referral__c r : referrals) {
if (ReferralChanges.needsRouting(r, oldMap)) {
toRoute.add(r);
regions.add(r.Region__c);
}
}
if (toRoute.isEmpty()) return;
Map<String, List<Id>> coordinators = CoordinatorSelector.userIdsByRegion(regions); // 3 queries, once
Set<Id> everyone = new Set<Id>();
for (List<Id> ids : coordinators.values()) everyone.addAll(ids);
Map<Id, Integer> load = ReferralWorkload.openCounts(everyone); // 1 query, once
for (Referral__c r : toRoute) {
Id pick = leastLoaded(coordinators.get(r.Region__c), load);
r.Assigned_Coordinator__c = pick;
r.Routed_On__c = System.now();
if (pick != null) load.put(pick, load.get(pick) + 1);
}
}
private static Id leastLoaded(List<Id> candidates, Map<Id, Integer> load) {
Id best;
for (Id candidate : candidates ?? new List<Id>()) {
if (best == null || load.get(candidate) < load.get(best)) best = candidate;
}
return best;
}
}If a region has no active coordinator, pick stays null and the referral is saved unassigned, which the Flow handles. Failing the save would be worse: an intake agent cannot fix a missing coordinator. The queries behind CoordinatorSelector and ReferralWorkload are on the SOQL page.
And the validation that runs before it:
public inherited sharing class ReferralValidator {
public static void validate(List<Referral__c> referrals, Map<Id, Referral__c> oldMap) {
for (Referral__c r : referrals) {
if (r.Status__c == ReferralStatus.DECLINED && String.isBlank(r.Decline_Reason__c)) {
r.Decline_Reason__c.addError('Say why the referral was declined.');
}
Boolean leftNew = ReferralChanges.changed(r, oldMap, Referral__c.Status__c)
&& r.Status__c != ReferralStatus.NEW_REFERRAL;
if (leftNew && r.Region__c == null) {
r.Region__c.addError('Set a region before moving the referral on.');
}
}
}
}addError on the field puts the message next to the input in the UI and in the API response, per record, so one bad row in a bulk load does not fail the other 199 when the caller uses partial success.
Why the logic is not in the trigger
- Testability. A service method takes a list and returns or mutates it. A unit test builds records in memory and calls it, no DML needed for most cases.
- One path in. The same service is called from the trigger, from the batch and from anything else that must apply the rule. A rule copied into a trigger body can only be exercised by saving records.
- Order and recursion in one place. The framework decides what runs when. The trigger file is never edited to change behaviour, so the diff for a rule change shows a rule change.
- Bulk by construction. The signature
List<Referral__c>makes the single-record version impossible to write by accident.