Sub topic 10
A practical framework for choosing
This chapter assumes you know the Salesforce data model, can navigate Setup, have built a simple record-triggered flow, and understand variables, loops, and collections. It gives you a repeatable way to decide whether a requirement belongs in Flow, in Apex, or in both. The earlier chapters covered what each tool is. Here you apply that knowledge.
Start from the requirement, not the tool
Teams often pick a tool by habit. Admins reach for Flow, and developers reach for Apex. Both habits produce avoidable problems. A better approach is to write the requirement as one plain sentence, then test it against a short list of questions.
For example, "When an opportunity closes won, create a renewal task for the owner" is a plain sentence. It names an event, an object, and an action. That is a strong sign that Flow fits.
"When a contact is inserted, recalculate the contact count on its account, even during a 50,000-row data load" adds scale and an aggregate calculation. That pushes toward Apex.
The default: declarative first
Use Flow first when it can meet the requirement. Flow has these advantages:
- Admins can build and change it without a developer.
- It deploys without writing test classes, although you should still test it.
- Its logic is visible on a canvas, so more people can review it.
- It carries less long-term maintenance cost for typical business rules.
"Flow first" is a default, not a rule. You move to Apex when a specific reason outweighs these advantages.
The five questions
Ask these questions in order. Stop at the first one that gives a clear answer.
- Can the requirement be expressed with Flow's built-in elements? Flow handles field updates, record creation, simple decisions, loops over small collections, screens, emails, and approvals. If yes, continue. If you would need to fight the tool, the answer leans toward Apex.
- Does it need something Flow cannot do? Examples are complex string or data-structure manipulation, custom REST or SOAP callouts with detailed control, custom parsing, reading platform events with complex handling, Apex-managed sharing, and logic that must be unit tested at a fine grain. If yes, use Apex.
- What is the volume and complexity? A flow can process many records in a bulk transaction, but a deeply nested flow with many loops and decisions is hard to read and slow to debug. If the logic needs dozens of elements to express what ten lines of code would say, consider Apex.
- Who will maintain it? If the team that owns the automation has no developers, an Apex solution becomes a risk. If the team has developers and strong source control, Apex is a reasonable choice.
- What are the testing and deployment requirements? Apex needs tests with at least 75% overall code coverage for production deployment. Flow does not have this requirement, but your release process may demand tests anyway.
Decision flow
The diagram below summarizes the questions as one path.
Criteria compared
The table below puts the main criteria side by side.
| Criterion | Flow is a better fit when | Apex is a better fit when |
|---|---|---|
| Logic shape | Steps are linear, with a few decisions | Logic needs complex algorithms, recursion, or custom data structures |
| Integration | Standard actions or simple HTTP callouts are enough | You need custom authentication, parsing, retries, or large payloads |
| Team skills | Admins own the automation | Developers own the automation |
| Testing | Debug runs and manual checks are acceptable | You need automated, repeatable unit tests |
| Change frequency | Business rules change often | Rules are stable and need strict review |
| Reuse | One process, one object | Logic is shared across triggers, APIs, batch jobs, and flows |
| Volume | Normal interactive and moderate bulk loads | Heavy aggregation or processing that needs tight control over queries |
Worked example 1: a simple rule
Requirement: "When a case is escalated, set its priority to High and notify the support manager."
Walk through the questions:
- Built-in elements: an Update Records element and a Send Email action cover it.
- Anything Flow cannot do: no.
- Volume and complexity: low.
- Maintenance: a support admin can own it.
- Testing: a manual check and a debug run are enough.
Decision: Flow alone. Writing a trigger here adds a test class, a deployment step, and a developer dependency for no benefit.
Worked example 2: a rule that needs code
Requirement: "After contacts are inserted, store the total number of contacts on each account. Data loads can insert thousands of contacts at once."
The logic needs an aggregate count grouped by account. Flow can do something similar by looping and counting, but the flow would hold a collection of records and loop over it, which is awkward and harder to keep within limits at scale. Apex does this with one aggregate query and one update:
trigger ContactTrigger on Contact (after insert) {
Set<Id> accountIds = new Set<Id>();
for (Contact c : Trigger.new) {
if (c.AccountId != null) {
accountIds.add(c.AccountId);
}
}
List<Account> toUpdate = new List<Account>();
for (AggregateResult ar : [
SELECT AccountId acctId, COUNT(Id) total
FROM Contact
WHERE AccountId IN :accountIds
GROUP BY AccountId
]) {
toUpdate.add(new Account(
Id = (Id) ar.get('acctId'),
Contact_Count__c = (Integer) ar.get('total')
));
}
update toUpdate;
}The trigger collects the account IDs, runs one grouped query, and issues one update for all affected accounts. The code assumes a number field named Contact_Count__c exists on Account. The test below checks it with 200 contacts in a single insert, which is the size of one trigger batch:
@IsTest
private class ContactTriggerTest {
@IsTest
static void countsContactsInBulk() {
Account a = new Account(Name = 'Acme');
insert a;
List<Contact> contacts = new List<Contact>();
for (Integer i = 0; i < 200; i++) {
contacts.add(new Contact(LastName = 'Contact ' + i, AccountId = a.Id));
}
insert contacts;
a = [SELECT Contact_Count__c FROM Account WHERE Id = :a.Id];
Assert.areEqual(200, a.Contact_Count__c);
}
}Decision: Apex. The aggregate query, the bulk behavior, and the automated test all favor code.
A note on this choice: a rollup summary field would be simpler still if the relationship allows it. Contact to Account is a lookup relationship, not master-detail, so a native rollup field is not available. Always check for a built-in feature before choosing either tool.
Worked example 3: use both
Requirement: "When an opportunity moves to Negotiation, a sales manager can enter a discount percent on a screen, and the system reduces the opportunity amount."
The screen, the decision on stage, and the notification are natural Flow work. The amount math is small but benefits from tested code, and other automations may reuse it. Expose it as an invocable method and call it from the flow:
public with sharing class ApplyDiscountAction {
public class Request {
@InvocableVariable(required=true)
public Id opportunityId;
@InvocableVariable(required=true)
public Decimal percent;
}
@InvocableMethod(label='Apply Discount' description='Reduces the Amount of each opportunity by the given percent')
public static void apply(List<Request> requests) {
Map<Id, Decimal> percentById = new Map<Id, Decimal>();
for (Request r : requests) {
percentById.put(r.opportunityId, r.percent);
}
List<Opportunity> opps = [
SELECT Id, Amount FROM Opportunity WHERE Id IN :percentById.keySet()
];
for (Opportunity opp : opps) {
if (opp.Amount != null) {
opp.Amount = opp.Amount * (100 - percentById.get(opp.Id)) / 100;
}
}
update opps;
}
}The method takes a list, so Flow can pass many requests in one call. It runs one query and one update regardless of how many requests arrive. Admins keep ownership of the flow, and developers own the tested method. The next chapter covers the mechanics of this pattern in more detail.
Decision: both.
Edge cases and common mistakes
- Choosing Apex because the flow "looks messy." A messy flow is often a design problem. Split it into subflows, name elements clearly, and add descriptions before you rewrite it in code.
- Choosing Flow because Apex "feels heavy." If the flow grows past what one person can hold in their head, the maintenance cost has already exceeded the cost of code.
- Ignoring limits. Both tools share governor limits inside one transaction. A flow that is fine for one record can fail on a bulk load, and Apex that queries inside a loop fails the same way.
- Stacking automations on one object. If a flow and a trigger both run on the same object and event, they run in the same transaction, and their order is not something you should rely on. Pick one owner per object and event where you can.
- Skipping the requirement for an owner. Whoever builds the automation, name who will fix it at 2 a.m. when it fails.
A short checklist
Use this list in design reviews:
- Is there a configuration feature that solves it without automation?
- Can Flow express it in a readable way?
- Does it need a capability only Apex has?
- Does it have to survive large, bulk data loads?
- Who owns it, and can they maintain it?
- How will it be tested before and after deployment?
- Does another automation already run on this object and event?
If every answer points to Flow, build the flow. If one answer blocks Flow, use Apex for that part. If the answers are mixed, use Flow for the orchestration and Apex for the specific steps that need code.
Exercise
A requirement says: "When a lead is created from the web form, assign it to the owner based on region, and send the owner an email." The region rules change every quarter, and the sales operations admin maintains them. Which tool should you choose, and which two criteria from this chapter justify the choice?
Show answer
Choose Flow. The logic is a linear sequence of a decision, an assignment, and an email, which Flow's built-in elements cover. The rules change often and an admin owns them, so declarative ownership and change frequency favor Flow. You should also check whether lead assignment rules already cover the region logic, since that configuration feature would cost even less to maintain.
Exercise
A flow calls out to a partner API that returns a large JSON document with nested arrays. The flow needs to read values from several levels of that structure, and the flow has grown to 60 elements. What does the framework suggest, and what is a lower-risk way to make the change?
Show answer
The framework suggests moving the parsing to Apex, because custom parsing and complex data-structure handling are capabilities Apex handles better and the flow has grown hard to read. A lower-risk approach is to keep the flow as the entry point and replace the parsing steps with a call to an invocable method that accepts a list of requests, parses the response, and returns the needed values. The method needs tests with at least 75% overall coverage before production deployment.