Sub topic 4
Where Apex Is the Better Choice
This chapter assumes you know the Salesforce data model (objects, fields, records), can find your way around Setup, and have built a simple Flow. It also assumes you know basic programming ideas such as variables, loops, and collections.
What Apex is
Apex is Salesforce's strongly typed, object-oriented language. It runs on the Salesforce platform, in the same transaction as the data it changes. Flow is the first tool to try for most automation. Some requirements need more control than a flow gives you, and Apex covers those.
Requirements that call for Apex
Look at the requirement first, then choose the tool. These signs point toward Apex:
- Complex logic. You need nested loops, recursion, or algorithms over large collections. Flows can express this, but they become hard to read and slow to change.
- Aggregation across related records. For example, counting child records and writing the total to the parent.
- Custom integrations. You need full control of HTTP callouts, request signing, retries, or response parsing.
- Reusable services. Several triggers, flows, and APIs need to call the same logic.
- Fine control over errors and transactions. You need savepoints, partial-save behavior, or custom exception handling.
- Precise testing needs. You want unit tests with assertions that run in every deployment.
Example: counting contacts per account
Suppose each Account must show how many Contacts it has. A custom number field Contact_Count__c on Account holds the value. A flow could do this, but you would need a loop, a lookup, and careful handling of many accounts per transaction. In Apex, one aggregate query covers all the records.
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;
}Walk through what it does:
Trigger.newholds every Contact in the batch, up to 200 at a time.- The first loop collects the unique account IDs into a
Set. - One
SELECT ... GROUP BYquery returns a count per account. - The second loop builds a list of Accounts with the new counts.
- A single
updatesaves them all.
The trigger runs one query and one DML statement (a data change such as insert or update) whether 1 contact or 200 contacts are inserted. This is called being bulk-safe.
Testing is part of the cost
Apex needs tests before it can go to production. Deployment requires at least 75% overall code coverage. Good tests also check behavior. This test inserts 200 contacts at once to prove the trigger works in bulk.
@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);
}
}Testing at the 200-record boundary is a habit worth keeping. It exposes queries or DML placed inside loops, which would break governor limits.
Common errors when choosing Apex
- Choosing Apex by habit. If a flow meets the need and the team can maintain it, code adds cost without benefit.
- Query or DML inside a loop. This works for one record and fails at 200. Collect IDs first, then query once.
- Skipping the bulk test. A test with a single record hides limit problems.
- No owner. Code needs a developer to maintain it. Confirm one exists before you commit.
Summary of the decision
| Situation | Better fit |
|---|---|
| Simple field update on save | Flow |
| Aggregation over many related records | Apex |
| Complex callout with custom retry logic | Apex |
| Logic reused by many entry points | Apex |
| Admin-owned process that changes often | Flow |
Exercise
A requirement says that when Contacts are inserted, each parent Account must store the total number of its Contacts. Why does the trigger in this chapter collect account IDs into a Set before it queries?
Show answer
The Set gathers the unique account IDs from every Contact in the batch. That lets the trigger run one aggregate query for all accounts instead of one query per contact. This keeps it inside the governor limit on queries and makes it bulk-safe.
Exercise
Why does the test insert 200 contacts instead of one?
Show answer
Triggers receive records in batches of up to 200. A test at that size shows whether the trigger stays within governor limits and works for the whole batch. A one-record test would pass even if a query or update sat inside a loop.