ApexSensei

Blog

Apex Best Practices: 10 Tips Every Salesforce Developer Should Know

By Firus Hanov · · 8 min read

Master the essential Apex coding standards and best practices that separate junior developers from senior Salesforce engineers. From bulkification to governor limits, learn the 10 tips every developer needs.

Apex Best Practices: 10 Tips Every Salesforce Developer Should Know

Why Apex Best Practices Matter

Writing Apex code that works is one thing — writing Apex code that scales, performs, and passes code review is another. Whether you're preparing for a Salesforce certification or working on enterprise-level projects, these 10 best practices will elevate your development skills.

1. Always Bulkify Your Code

The #1 rule of Apex development: never assume your code will process a single record. Salesforce triggers can fire on up to 200 records at once, and your code must handle all of them efficiently.

// ❌ Bad - processes one record at a time
for (Account acc : Trigger.new) {
    Contact c = [SELECT Id FROM Contact WHERE AccountId = :acc.Id LIMIT 1];
}

// ✅ Good - bulkified
Set<Id> accountIds = new Set<Id>();
for (Account acc : Trigger.new) {
    accountIds.add(acc.Id);
}
Map<Id, Contact> contactMap = new Map<Id, Contact>(
    [SELECT Id, AccountId FROM Contact WHERE AccountId IN :accountIds]
);

2. Respect Governor Limits

Salesforce enforces governor limits to ensure shared resources are used fairly. Key limits to watch:

  • 100 SOQL queries per synchronous transaction
  • 150 DML statements per transaction
  • 10,000 records retrieved by SOQL queries
  • 6MB heap size for synchronous Apex

Use Limits class methods like Limits.getQueries() and Limits.getDMLStatements() to monitor usage during development.

3. Write Meaningful Test Classes

Salesforce requires 75% code coverage, but aim for 90%+ with meaningful assertions. Don't just cover lines — test behavior.

@isTest
static void testAccountUpdate_ShouldUpdateRelatedContacts() {
    Account testAcc = TestDataFactory.createAccount();
    insert testAcc;
    
    testAcc.Name = 'Updated Name';
    update testAcc;
    
    List<Contact> relatedContacts = [
        SELECT Id, Account.Name FROM Contact WHERE AccountId = :testAcc.Id
    ];
    System.assertEquals('Updated Name', relatedContacts[0].Account.Name,
        'Contact should reflect updated account name');
}

4. Optimize SOQL Queries

Efficient SOQL is critical for performance. Always use selective filters, avoid SELECT * patterns, and leverage indexed fields in WHERE clauses.

  • Use Id, Name, CreatedDate, and custom indexed fields in filters
  • Avoid SOQL inside loops — query once, then iterate
  • Use relationship queries to reduce the number of queries

5. Use a Trigger Framework

Never put business logic directly in triggers. Use a trigger framework that separates concerns and makes your code testable and maintainable. Popular patterns include the Handler pattern and the Domain Layer pattern.

6. Leverage Asynchronous Apex

For heavy processing, use async methods to avoid governor limits:

  • Future methods — simple async callouts
  • Queueable Apex — chainable async jobs with complex data types
  • Batch Apex — process millions of records
  • Scheduled Apex — run code on a schedule

7. Implement Proper Error Handling

Use try-catch blocks strategically. Log errors to a custom object or platform event for monitoring. Never silently swallow exceptions.

8. Follow Security Best Practices

Always use WITH SHARING on classes unless you have a specific reason not to. Use stripInaccessible() to enforce field-level security, and always validate user input.

9. Use Consistent Naming Conventions

Follow Salesforce naming standards: PascalCase for classes, camelCase for methods and variables, UPPER_CASE for constants. Prefix test classes with Test or suffix with _Test.

10. Conduct Code Reviews

Every pull request should be reviewed for bulkification, governor limit compliance, test coverage, and security. Use tools like PMD and Salesforce Code Analyzer to automate static analysis.

Conclusion

Following these best practices will make you a more effective Salesforce developer and help you build applications that scale. Start applying these tips today, and practice them with hands-on coding challenges on ApexSensei.

Practice Apex free on ApexSensei