Apex best practices: bulkification, security, errors and configuration
The habits that make Apex survive production: set-based logic, user-mode data access, no hardcoded IDs, deliberate error handling, and configuration in custom metadata.
Simple explanation
1. Bulkify everything. Collect IDs into sets, query once, put results in maps, and do one DML per object type. Never query or DML inside a loop.
2. Respect the user's access. Apex runs in system mode by default, so be explicit:
- Classes declare
with sharing(orinherited sharingfor utilities). Usewithout sharingonly for a documented reason. - Queries use
WITH USER_MODE, and DML usesinsert as user/Database.insert(records, AccessLevel.USER_MODE), which enforce object and field permissions as well as sharing. - Dynamic SOQL uses bind variables, never string concatenation of user input.
3. Handle errors deliberately. Catch only what you can handle. Use Database.insert(records, false) for partial success and report the failures. Rethrow or log the rest. Don't swallow exceptions with an empty catch.
4. No hardcoded IDs or values. Look up record types by developer name, queues by name, and keep thresholds, endpoints and feature switches in custom metadata types (deployable, cached) or custom settings.
5. One responsibility per class. Triggers delegate to handlers, handlers to services. Code is testable without the UI.
6. Write tests that assert behaviour, with bulk data and different users. The 75% coverage rule is a floor, not a goal.
Real-world analogy
Bulkification is the difference between a waiter who takes one order, walks to the kitchen, comes back and takes the next order, and one who takes the whole table's order and makes one trip. Both work for a table of one. Only the second survives a table of 200.
Worked example
A service that closes cases for a set of accounts, bulk-safe and in user mode:
public with sharing class CaseClosureService {
public class ClosureResult {
public Integer closed = 0;
public List<String> errors = new List<String>();
}
public static ClosureResult closeOpenCases(Set<Id> accountIds, String resolution) {
ClosureResult result = new ClosureResult();
if (accountIds == null || accountIds.isEmpty()) {
return result;
}
List<Case> toClose = new List<Case>();
for (Case c : [
SELECT Id FROM Case
WHERE AccountId IN :accountIds AND IsClosed = false
WITH USER_MODE
]) {
toClose.add(new Case(Id = c.Id, Status = 'Closed', Resolution__c = resolution));
}
// Partial success: one bad record doesn't block the others.
List<Database.SaveResult> saves = Database.update(toClose, false, AccessLevel.USER_MODE);
for (Integer i = 0; i < saves.size(); i++) {
if (saves[i].isSuccess()) {
result.closed++;
} else {
for (Database.Error e : saves[i].getErrors()) {
result.errors.add(toClose[i].Id + ': ' + e.getMessage());
}
}
}
return result;
}
}
Configuration from custom metadata instead of a hardcoded value:
Integration_Setting__mdt setting = Integration_Setting__mdt.getInstance('Billing');
Integer timeoutMs = Integer.valueOf(setting.Timeout_Ms__c);
Diagram
Key points
- Sets β one query β maps β one DML per object. No SOQL or DML in loops.
with sharingby default;WITH USER_MODEandas userDML enforce CRUD, FLS and sharing.- Bind variables in dynamic SOQL; never concatenate user input.
- Partial-success DML (
allOrNone = false) with explicit error reporting. - No hardcoded IDs; configuration in custom metadata types.
- Small classes with one responsibility; tests that assert behaviour with bulk data and different users.
Limits and gotchas
with sharingenforces record sharing only, not object or field permissions. Use user mode (orSecurity.stripInaccessible) for CRUD and FLS.WITH SECURITY_ENFORCEDis the older option: it throws on the first inaccessible field.WITH USER_MODEis preferred for new code.- Partial success means the transaction still commits the successful rows. Make sure that's acceptable for the business process.
- Custom metadata reads with
getInstance/getAllare cached and don't use SOQL. SOQL queries on custom metadata generally don't count against the query limit either, with exceptions such as long text area fields β verify current behaviour. - Catching
Exceptionbroadly hides limit exceptions you can't recover from (LimitExceptioncan't be caught at all).
π€ How to say this in an interview
Expect "review this trigger" or "what's wrong with this code?". Name the bulkification issue first, then security (system mode, FLS), then maintainability (hardcoded IDs, logic in the trigger). Show the corrected version briefly.
Common follow-ups
What's the difference between `with sharing`, `without sharing` and `inherited sharing`?
with sharing enforces the running user's record sharing. without sharing ignores it. inherited sharing takes the caller's mode, and runs as with sharing when it's the entry point. None of them enforce object or field permissions; use user mode for that.
How do you make dynamic SOQL safe?
Use bind variables (:name, or Database.queryWithBinds with a map), whitelist field and object names against the schema describe, and run the query in user mode. Never concatenate raw user input into the query string.