Level up your Salesforce development game with these advanced and useful Apex code tricks:
Performance & Governor Limits
1. Bulkify Your Code
Details: Process multiple records in a single execution context to minimize governor limit consumption.
2. Use Collections Efficiently
Details: Employ List, Set, and Map appropriately for efficient data storage and retrieval.
3. SOQL For Loops for Large Datasets
Details: Use SOQL for loops to process records in batches and avoid the “Too many SOQL queries” limit.
4. Avoid SOQL/DML Inside Loops
Details: Always perform SOQL and DML operations outside of for loops.
5. Use Database.insert/update/delete with allOrNone = false
Details: Allow partial success for non-critical DML operations.
6. Limit the Number of Future/Queueable/Batchable Jobs
Details: Be mindful of asynchronous Apex governor limits.
7. Use Limits Class for Monitoring
Details: Track governor limit usage within your code.
8. Optimize SOQL Queries
Details: Write efficient SOQL queries with selective filters and limited fields.
9. Utilize WITH SECURITY_ENFORCED
Details: Enforce object and field-level security in SOQL queries.
10. Consider FOR UPDATE for Record Locking
Details: Use FOR UPDATE to lock records and prevent race conditions (use judiciously).
Code Efficiency & Best Practices
11. Write Testable Code
Details: Design classes with dependency injection and clear separation of concerns.
12. Follow Naming Conventions
Details: Use clear and consistent naming conventions.
13. Add Meaningful Comments
Details: Explain complex logic and non-obvious behavior.
14. Keep Methods Short and Focused
Details: Break down large methods into smaller, reusable units.
15. Avoid Hardcoding IDs and Values
Details: Use Custom Metadata Types, Custom Settings, or constants.
16. Use Constants for Reusable Strings and Numbers
Details: Define constants for reusable literal values.
17. Implement Error Handling
Details: Use try-catch blocks to handle exceptions gracefully.
18. Log Important Events
Details: Implement logging mechanisms for critical actions and debugging.
19. Use Static Variables for Shared Context
Details: Share data efficiently within a request (use cautiously).
20. Leverage Inheritance and Polymorphism
Details: Design classes with inheritance and interfaces for code reuse and flexibility.
Advanced SOQL & SOSL
21. Use Subqueries for Related Data
Details: Retrieve child records directly within the parent object’s SOQL query.
22. Understand Relationship Queries
Details: Master parent-to-child and child-to-parent relationship query syntax.
23. Use Aggregate Functions
Details: Perform calculations like COUNT(), SUM(), AVG(), etc., directly in SOQL.
24. Leverage GROUP BY and HAVING Clauses
Details: Group and filter aggregated results in SOQL.
25. Explore SOSL for Text-Based Searches
Details: Use SOSL for efficient text searches across multiple objects.
26. Understand SOSL Data Categories
Details: Be aware of FIND, IN SearchGroup, and RETURNING for effective SOSL searches.
Asynchronous Apex & Scheduling
27. Choose the Right Asynchronous Tool
Details: Understand the differences between Future, Queueable, and Batch Apex.
28. Chain Queueable Jobs
Details: Implement sequential processing of asynchronous tasks.
29. Use State in Batch Apex
Details: Maintain state across different execution contexts in Batch Apex.
30. Implement Robust Error Handling in Asynchronous Apex
Details: Handle exceptions and implement retry mechanisms or error logging.
31. Schedule Apex Jobs Dynamically
Details: Programmatically schedule Apex jobs based on specific criteria.
Triggers & Automation
32. One Trigger Per Object
Details: Follow the “one trigger per object” best practice.
33. Use a Trigger Framework
Details: Employ handler classes or service layers to manage trigger logic.
34. Avoid Hardcoding in Triggers
Details: Callout reusable helper classes from your triggers.
35. Be Mindful of Trigger Recursion
Details: Implement mechanisms to prevent infinite trigger loops.
36. Consider Platform Events for Decoupled Automation
Details: Use Platform Events for loosely coupled and scalable automation.
Integration & Callouts
37. Use @future(callout=true) for External Service Calls
Details: Make asynchronous callouts to external services.
38. Implement Callout Error Handling and Retries
Details: Handle potential errors and implement retry mechanisms.
39. Secure Callout Credentials
Details: Store sensitive credentials securely using Named Credentials.
40. Parse JSON and XML Responses Efficiently
Details: Use JSON.deserialize() and Dom.Document for parsing.
Testing Strategies
41. Write Positive and Negative Test Cases
Details: Test both successful scenarios and error conditions.
42. Test Bulk Operations
Details: Ensure your code handles bulk data correctly in tests.
43. Isolate Test Data
Details: Create test data within your test methods.
44. Use Test.startTest() and Test.stopTest()
Details: Enclose asynchronous operations within these blocks.
45. Assert Expected Outcomes
Details: Use System.assert() methods to verify code behavior.
Advanced Language Features
46. Use Enums for Enumerated Values
Details: Employ enums for a set of named constants.
47. Leverage Interfaces for Contract-Based Programming
Details: Define contracts using interfaces for polymorphism.
48. Explore Inner Classes
Details: Use inner classes to logically group related functionality.
49. Understand Exception Handling Hierarchy
Details: Be familiar with different types of exceptions in Apex.
50. Stay Updated with New Apex Features
Details: Continuously learn about new features in each Salesforce release.
Leave a Reply