⚡
SF DEV TOOLKIT
Apex · SOQL · LWC · Patterns
API v62.0
Best Practices
Apex Design Patterns
Production-grade patterns for bulkification, error handling, and scalable architecture.
✅ Bulkified Service Class
GOOD Apex
public class AccountService {

    // One SOQL for the entire batch — never query inside a loop
    public static void enrichAccounts(List<Account> accounts) {
        Set<Id> accountIds = new Set<Id>();
        for (Account acc : accounts) {
            accountIds.add(acc.Id);
        }

        // Aggregate child data in one query
        Map<Id, AggregateResult[]> oppMap = new Map<Id, AggregateResult[]>();
        for (AggregateResult ar : [
            SELECT AccountId, COUNT(Id) cnt, SUM(Amount) total
            FROM Opportunity
            WHERE AccountId IN :accountIds
            AND StageName = 'Closed Won'
            GROUP BY AccountId
        ]) {
            Id accId = (Id) ar.get('AccountId');
            if (!oppMap.containsKey(accId)) {
                oppMap.put(accId, new AggregateResult[]{});
            }
            oppMap.get(accId).add(ar);
        }

        List<Account> toUpdate = new List<Account>();
        for (Account acc : accounts) {
            if (oppMap.containsKey(acc.Id)) {
                AggregateResult ar = oppMap.get(acc.Id)[0];
                acc.NumberOfEmployees = (Integer) ar.get('cnt');
                toUpdate.add(acc);
            }
        }

        // Database.update with allOrNone=false for partial success
        List<Database.SaveResult> results =
            Database.update(toUpdate, false);

        ErrorHandler.logSaveResults(results, toUpdate);
    }
}
❌ Anti-Pattern: SOQL In Loop
AVOID Apex
// ❌ This hits governor limits at just 101 records!
for (Account acc : accounts) {
    List<Contact> contacts = [
        SELECT Id, Name FROM Contact
        WHERE AccountId = :acc.Id   // SOQL inside a loop!
    ];
    acc.Description = 'Has ' + contacts.size() + ' contacts';
}

// ✅ Fix: query once, use a Map for O(1) lookups
Map<Id, List<Contact>> contactsByAccount = new Map<Id, List<Contact>>();
for (Contact c : [
    SELECT Id, AccountId FROM Contact
    WHERE AccountId IN :accountIds
]) {
    if (!contactsByAccount.containsKey(c.AccountId))
        contactsByAccount.put(c.AccountId, new List<Contact>());
    contactsByAccount.get(c.AccountId).add(c);
}
Batch Apex — Chunked Processing
Pattern Apex
global class AccountBatch implements Database.Batchable<sObject>,
                                                    Database.Stateful {

    global Integer processedCount = 0;  // Stateful across chunks

    global Database.QueryLocator start(Database.BatchableContext bc) {
        return Database.getQueryLocator([
            SELECT Id, Name, AnnualRevenue
            FROM Account
            WHERE AnnualRevenue > 0
        ]);
    }

    global void execute(Database.BatchableContext bc,
                          List<Account> scope) {
        // scope size = batchSize (default 200, max 2000)
        List<Account> toUpdate = new List<Account>();
        for (Account acc : scope) {
            acc.Rating = acc.AnnualRevenue > 1000000 ? 'Hot' : 'Warm';
            toUpdate.add(acc);
        }
        update toUpdate;
        processedCount += scope.size();
    }

    global void finish(Database.BatchableContext bc) {
        System.debug('Processed: ' + processedCount + ' records');
        // Chain another batch or send notification
    }
}

// Execute: Database.executeBatch(new AccountBatch(), 200);