Process Automation and Logic
Order of execution is the syllabus
Most logic questions are really order-of-execution questions. On save, the platform approximately: loads or initializes the record, runs before-save record-triggered flows, runs before triggers, applies system validation, applies custom validation rules, applies duplicate rules, saves to the database, runs after triggers, then assignment rules, auto-response rules and workflow rules, then after-save flows, then roll-up summaries, then commits. Post-commit, emails and asynchronous work run. Workflow field updates are special: they cause before and after update triggers to fire again once.
Concepts
- Trigger contexts:
isBefore,isAfter,isInsert,isUpdate,isDelete,isUndelete, andTrigger.new,Trigger.old,Trigger.newMap,Trigger.oldMap.Trigger.newis writable in before triggers and read-only in after triggers. - Bulkification: one invocation handles up to 200 records; loops must not contain SOQL or DML.
- Handler pattern: one trigger per object delegating to a class keeps execution order deterministic and testable.
- Recursion control: a static
Set<Id>of processed record Ids. - Asynchronous Apex:
@futuretakes primitives and cannot chain; Queueable accepts complex types and can chain; Batch handles large volumes, optionallyDatabase.Stateful; Schedulable runs on a schedule.
Trap
Changing a field on the same record in an after trigger requires a DML update - wasteful and recursion-prone. Do it in a before trigger or a before-save flow. Also remember a record-triggered flow and a trigger on the same object both fire, and nothing guarantees your Apex runs after the flow.
Rule of thumb
Ask "before or after the save?" If the change is to the same record and needs no Id, before. If it depends on the Id, on children, or on other records, after.