Sub topic 21
Where to put your logic
This chapter assumes you can write a basic Apex trigger, know the order of execution from the earlier chapters, and have used Flow and validation rules. It turns that order into decision rules for choosing where each piece of logic goes.
Start with the question, not the tool
Ask three questions about each requirement, in this order:
- Does it need to change the record being saved, or only react to it?
- Does it need the record's Id, or data from other records?
- Can it run after the save is final, or must it be part of the transaction?
The answers point to a step in the order of execution.
Placement rules
| Need | Best place | Reason |
|---|---|---|
| Set or default fields on the same record | Before-save flow or before trigger | The values are saved with the record. No extra DML statement is needed. |
| Block a save based on field values | Validation rule | It is declarative and runs after before triggers, so it sees their changes. |
| Block a save based on logic a rule cannot express | Before trigger with `addError` | The error rolls back the whole transaction. |
| Create child or related records | After-save flow or after trigger | The new record's Id exists only after the database save. |
| Update parent records | After trigger or after-save flow | You are changing other records, so this is a separate DML operation. |
| Callouts, large processing, email | Asynchronous Apex | Callouts are not allowed mid-transaction. Slow work should not block the save. |
Prefer the simplest tool that works
A before-save flow is the cheapest way to change fields on the triggering record. It does not issue DML and runs before triggers. Use it for defaults and simple derived values.
Use Apex when you need any of these:
- Complex branching or collections that are awkward in Flow.
- Fine control over recursion.
- Unit-testable logic with explicit assertions.
- Logic shared by several entry points, such as a trigger, a batch job, and an API.
Neither tool is always better. What matters is that each object has a clear owner for each kind of logic.
One trigger per object, thin and bulk-safe
Salesforce does not guarantee the order of multiple triggers on the same object. Keep one trigger per object and send the work to a class. The trigger only routes by context.
trigger AccountTrigger on Account (before insert, before update, after insert) {
if (Trigger.isBefore) {
AccountService.applyDefaults(Trigger.new);
} else if (Trigger.isAfter && Trigger.isInsert) {
AccountService.createFollowUps(Trigger.new);
}
}public class AccountService {
public static void applyDefaults(List<Account> accounts) {
for (Account a : accounts) {
if (String.isBlank(a.Description)) {
a.Description = 'Created without a description';
}
}
}
public static void createFollowUps(List<Account> accounts) {
List<Task> tasks = new List<Task>();
for (Account a : accounts) {
tasks.add(new Task(Subject = 'Follow up', WhatId = a.Id));
}
insert tasks;
}
}applyDefaults assigns to Trigger.new records and uses no DML, which is correct in a before context. createFollowUps reads a.Id, which exists only after the insert, and it inserts all tasks in one statement, whatever the batch size.
Plan for the whole transaction
Your logic does not run alone. Flows, other triggers, workflow field updates, and roll-up summaries all run in the same transaction and share the same governor limits. Keep these habits:
- Never put SOQL or DML inside a loop. Collect Ids, query once, and use a
Mapfor lookups. - Count what your automation costs. Two flows and a trigger that each query the same object use three queries per save, and that grows with every chained update.
- Update only records that changed. Compare
Trigger.oldMapwith the new values before you add a record to an update list. - Guard against re-entry. A workflow field update can fire before and after update triggers again. Track processed Ids in a static
Set<Id>, as in the recursion chapter, or better, check whether the relevant field actually changed.
Failure and side effects
Anything that must be undone when the save fails belongs inside the transaction. Anything that must not happen unless the save commits belongs after it. Sending an email or calling an external system from a trigger can announce a change that is later rolled back. Queue that work with System.enqueueJob, or publish a platform event after commit, so it only runs once the data is final.
A quick review checklist
- Is each piece of logic in the earliest step that has what it needs?
- Does the before logic avoid DML and avoid reading the Id on insert?
- Does the after logic avoid editing
Trigger.newrecords directly? - Is there one trigger per object, and is each flow's purpose distinct from it?
- Are queries and DML bulk-safe, and is recursion controlled by Id or by field change?
- Is slow or external work moved out of the save transaction?
Exercise
A requirement says: when an Opportunity is inserted, copy the Account's Industry onto a custom field of the Opportunity, and create a Task for the owner that references the Opportunity. Which step handles each part, and why?
Show answer
Copying Industry changes a field on the saved record, so it goes in a before-save flow or a before trigger. It needs no DML on the record, and the value is saved with it. Querying the Accounts should be done once for all records in the batch. Creating the Task needs the Opportunity's Id, which exists only after the database save, so it goes in an after-save flow or an after trigger, with all Tasks inserted in one DML statement.
Exercise
A trigger sets a static Boolean alreadyRan = true to stop recursion after a workflow field update. During a 500-record data load, some records are never processed. Why, and what is a safer approach?
Show answer
The load runs in chunks of 200 records in the same transaction. The first chunk sets the flag, so the trigger skips the later chunks. A safer approach is a static Set<Id> of processed record Ids, or a check that compares Trigger.oldMap with the new values and acts only when the relevant field changed.