Mastering Apex Triggers: Best Practices for Salesforce Developers
Mastering Apex Triggers: Best Practices
1. One Trigger Per Object
Avoid having multiple triggers on the same object. Instead, consolidate logic into a single trigger and delegate
functionality to handler classes. This keeps your triggers organized and prevents unintended behavior.
2. Use Trigger Frameworks
Implement a trigger framework (e.g., Trigger Handler Pattern) to structure your code. This ensures separation of
concerns, making the trigger easier to debug and extend.
3. Bulkify Your Code
Always design your triggers to handle bulk operations, even if the current use case involves single records. Use
collections like List, Set, and Map to avoid hitting governor limits.
Example:
// Avoid DML in a loop
List<Account> accountsToUpdate = new List<Account>();
for (Contact c : Trigger.new) {
if (c.Email != null) {
accountsToUpdate.add(new Account(Id = c.AccountId, LastContacted = Date.today()));
update accountsToUpdate;
Mastering Apex Triggers: Best Practices for Salesforce Developers
4. Avoid Hardcoding Logic
Use Custom Metadata Types, Custom Settings, or Custom Labels instead of hardcoding values. This makes your code
reusable and easier to maintain.
5. Enforce Trigger Order
Avoid writing logic that depends on the order of execution. For dependencies, use helper classes with clearly defined
methods to enforce a consistent flow.
6. Write Comprehensive Test Classes
Cover all possible scenarios in your test classes: single record, bulk processing, and edge cases. Aim for at least 90%
code coverage while focusing on testing business logic, not just lines of code.
7. Follow Salesforce Governor Limits
Be mindful of SOQL/DML limits. Use Map and batch processing to minimize SOQL queries and DML operations.
8. Document Your Triggers
Add comments to explain the trigger's purpose and the logic in your handler classes. This helps future developers (and
even yourself) understand the code better.
9. Use Context Variables Wisely
Use Trigger.new, Trigger.old, and other context variables to identify changes and prevent recursion. For example, avoid
infinite loops by tracking processed records in a Set.
Mastering Apex Triggers: Best Practices for Salesforce Developers
Pro Tip: Refactor!
If your trigger logic becomes complex, break it down into smaller, reusable methods in the handler class. This improves
readability and makes testing a breeze.