Sub topic 4
Where Apex is the better choice
This chapter assumes you can build a simple record-triggered flow, find your way around Setup, and read basic code (variables, loops, lists, maps). You don't need to have written Apex before. The goal is to learn which requirements push you toward code.
Flow should be your first choice for many requirements, as the previous chapter explained. Apex becomes the better choice when a requirement needs control that a declarative tool does not give you. That control falls into a few groups, described below.
Complex logic and data structures
Flow works well with records and collections of records. It gets awkward when logic needs richer structures or many nested steps.
Apex gives you:
- Maps, sets, and lists of any type, including nested ones such as
Map<Id, List<Contact>>. - Your own classes, with fields, methods, and interfaces.
- Recursion, helper methods, and reusable libraries.
- Exceptions you can throw and catch with
try/catch/finally. - String, date, and JSON utilities that go well beyond flow formulas.
A flow that grows past 30 or 40 elements, with nested loops, many decision branches, and assignments that copy values between collections, is often a sign that the logic wants to be code. A 60-line Apex method with named variables is usually easier to read than the same logic spread over a canvas.
Choosing between loops in Flow and loops in Apex
Both tools can loop over records. The difference is in what you can do with the results. In Apex you can group records into a map keyed by account Id in one pass and then look up any group in constant time. In Flow you would typically need a loop inside a loop, which is harder to read and easier to get wrong.
Fine control over transactions and errors
Flow offers fault paths, which let you route a failed element to an error-handling branch. Apex offers more:
- Partial success.
Database.insert(records, false)saves the valid records and returns an error for each invalid one, instead of failing the whole batch. - Savepoints.
Database.setSavepoint()andDatabase.rollback()let you undo part of a transaction while keeping the rest. - Precise error reporting.
addError()on a record or field in a trigger blocks the save and shows the message on a chosen field. - Custom exception types that carry the information callers need.
The example below inserts contacts and collects the failures instead of letting one bad record stop the others.
public with sharing class ContactImporter {
public static List<String> importContacts(List<Contact> contacts) {
List<Database.SaveResult> results = Database.insert(contacts, false);
List<String> errors = new List<String>();
for (Integer i = 0; i < results.size(); i++) {
if (!results[i].isSuccess()) {
for (Database.Error err : results[i].getErrors()) {
errors.add(contacts[i].LastName + ': ' + err.getMessage());
}
}
}
return errors;
}
}The loop uses an index so each result can be matched to the record at the same position. Salesforce returns results in the same order as the input list.
Integrations and callouts
A callout is a request from Salesforce to an external system. Flow can make callouts in some cases, such as through External Services or HTTP Callout actions. Apex is still the more flexible option when you need to:
- Build headers, authentication steps, and request bodies in code.
- Parse nested JSON responses and map them to records.
- Retry, branch on status codes, or call several endpoints in sequence.
- Expose your own REST or SOAP endpoint with
@RestResourceor awebservicemethod so other systems can call Salesforce.
Callouts also have a timing rule. You can't make a callout from a trigger's synchronous context after uncommitted data changes have been made. The usual pattern is to hand the work to asynchronous Apex. The class below does that with a Queueable job. It assumes a Named Credential called Billing_API exists in your org.
public with sharing class BillingSyncJob implements Queueable, Database.AllowsCallouts {
private final Set<Id> accountIds;
public BillingSyncJob(Set<Id> accountIds) {
this.accountIds = accountIds;
}
public void execute(QueueableContext context) {
for (Account a : [SELECT Id, Name FROM Account WHERE Id IN :accountIds]) {
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:Billing_API/accounts');
req.setMethod('POST');
req.setHeader('Content-Type', 'application/json');
req.setBody(JSON.serialize(new Map<String, Object>{
'id' => a.Id,
'name' => a.Name
}));
HttpResponse res = new Http().send(req);
if (res.getStatusCode() >= 300) {
System.debug(LoggingLevel.ERROR,
'Billing sync failed for ' + a.Id + ': ' + res.getStatus());
}
}
}
}You start the job with System.enqueueJob(new BillingSyncJob(accountIds));. Apex allows up to 100 callouts in one transaction, so a job like this must stay under that cap or split its work into smaller jobs.
Volume and asynchronous processing
Apex has several asynchronous tools built for large data volumes and scheduled work:
| Tool | Use it when |
|---|---|
| Queueable Apex | You need background work, chaining, or callouts after a trigger |
| Batch Apex | You need to process thousands or millions of records in chunks, each with fresh governor limits |
| Schedulable Apex | A job should run on a schedule you control in code |
| Platform event triggers | You react to events published by other systems or processes |
Flow has scheduled flows and asynchronous paths, and they cover many needs. Batch Apex still gives you control over chunk size, state held between chunks (Database.Stateful), and a finish method that runs when everything is done. For data cleanup or recalculation across a very large table, it is often the safer tool.
Security and sharing control
Apex runs in system context by default, which means it can ignore the running user's permissions unless you say otherwise. This is a power and a risk. You decide how it behaves:
with sharingmakes the class respect the user's record access.WITH USER_MODEin SOQL, orDatabase.insert(records, AccessLevel.USER_MODE), enforces field and object permissions.without sharingis available for the rare case where code must see everything, and it should be rare.
Apex can also create sharing records for custom access rules, which Flow cannot express in the same detail. If a requirement says "share this record with the partner users listed on a related object," that is a candidate for code.
Dynamic and metadata-driven behavior
Flow is built around fixed objects and fields chosen at design time. Apex can decide at run time:
- Dynamic SOQL with
Database.query()builds a query from a variable object or field name. Use bind variables orString.escapeSingleQuotes()for any user-supplied value. - Schema describe calls, such as
Schema.getGlobalDescribe(), discover objects and fields. - Custom metadata types combined with Apex let admins change rules without a deployment while the engine itself stays in code.
This matters for generic frameworks, such as one trigger handler that works for many objects, or a rule engine configured by records.
Performance and tight limits
Both tools share the same governor limits, covered in the next chapter, but Apex gives you more ways to stay inside them. You can:
- Query only the fields you need and filter selectively.
- Cache results in static variables for the life of a transaction.
- Combine several lookups into one query.
- Exit early, skipping work when nothing relevant has changed.
A before-save record-triggered flow is very fast, and it is the right choice for simple field updates. When a flow has to run many queries, loops, and updates, Apex tends to give you more predictable resource use.
Quality practices: tests, source control, and reuse
Apex code is plain text. It fits naturally into version control, code review, diff tools, and continuous integration. Apex also has unit tests that can check individual methods, and production deployment requires at least 75% overall code coverage. A later chapter covers this in full. For now, note the practical benefit: you can write a test that inserts 200 records and asserts the result, which gives you a repeatable safety net.
@IsTest
private class ContactImporterTest {
@IsTest
static void reportsFailuresWithoutStoppingValidRecords() {
List<Contact> contacts = new List<Contact>{
new Contact(LastName = 'Valid'),
new Contact() // missing required LastName
};
List<String> errors = ContactImporter.importContacts(contacts);
Assert.areEqual(1, errors.size(), 'Only the invalid record should fail');
Assert.areEqual(1, [SELECT COUNT() FROM Contact WHERE LastName = 'Valid']);
}
}Code can also be reused. One Apex class can serve a trigger, a batch job, a REST endpoint, and a flow action. That reuse is the basis of the hybrid pattern in a later chapter.
Signals that point to Apex
The diagram shows a quick screening path. Treat it as a starting point and not as a rule.
Costs of choosing Apex
Apex is not free of drawbacks. Weigh these before you commit:
- Skills. Someone must be able to read, debug, and change the code. If your only developer leaves, the automation can become a liability.
- Delivery process. Apex needs a sandbox, tests, and a deployment. A small change that takes minutes in Flow can take days through a release process.
- Visibility. Admins can open a flow and see the logic. Apex needs a developer or a good set of comments and documentation.
- Bulk responsibility. In Apex, nothing stops you from writing a query inside a loop. Flow's builder gives some protection against this. Apex gives none, so bulk safety is your job.
Worked comparison
Consider three requirements and where each one lands.
- "When an opportunity is Closed Won, create a follow-up task for the owner." This is a simple record-triggered flow.
- "When contacts change, keep a count on the account and block the save if the count would pass a limit that depends on the account's tier from a custom metadata type." This involves aggregation, a lookup keyed by tier, and a custom error. Apex is the better fit.
- "Every night, sync 500,000 customer records to an external billing system, retrying failures." This calls for Batch Apex with callouts, and likely Queueable retries.
The first stays in Flow. The second and third need code.
Exercise
A team needs a nightly job that updates 2 million records, keeps a running total across chunks, and sends one summary email when the job finishes. Which Apex feature suits this, and why?
Show answer
Batch Apex implementing Database.Stateful. It processes records in chunks, each with fresh governor limits. Database.Stateful keeps the running total between chunks. The finish method runs once at the end, so it is the place to send the summary email.
Exercise
A trigger calls Database.insert(records) on 200 records and one record fails validation. What happens to the other 199, and how would you change the call to save the valid ones?
Show answer
With the default all-or-none behavior, the whole operation fails and none of the 199 are saved. Pass false as the second argument, Database.insert(records, false), so valid records are saved, and then inspect each Database.SaveResult to report the failures.
Exercise
You need a flow to apply one specialized pricing calculation that depends on a Map of tier rules. List two reasons to put only that calculation in Apex instead of rebuilding the whole flow in code.
Show answer
The rest of the flow stays visible and editable by admins, so maintenance stays cheap. Only the small calculation needs the code skills, tests, and deployment process, and that class can be reused elsewhere.