Mastering Apex Governor Limits: Best Practices for Robust Code

Dealing with governor limits can be a source of frustration for any developer. But, since we can't escape them, the smart move is to enhance our code quality by adhering to best practices while writing Apex. To help you navigate this challenging terrain, we've compiled a list of fundamental governor limits you should always consider when crafting your code.


1. SOQL Queries (Select Queries)

- Limit: 100 queries in synchronous transactions.

- Best Practice: Minimize database queries by bulkifying operations and using collections to retrieve or update records whenever possible.


2. DML Statements (Database Manipulation)

- Limit: 150 DML statements in synchronous transactions.

- Best Practice: Use bulk DML operations to reduce the number of DML statements in your code.


3. CPU Time

- Limit: 10,000 milliseconds (10 seconds) in synchronous transactions.

- Best Practice: Optimize your code for efficiency and avoid unnecessary loops or recursive processes.


4. Heap Size (Memory Consumption)

- Limit: 6MB for synchronous transactions.

- Best Practice: Be mindful of memory consumption, and avoid storing large data sets in memory.


5. Callouts (External Web Service Requests)

- Limit: 100 HTTP callouts in synchronous transactions.

- Best Practice: Use asynchronous Apex or batch processing for long-running or bulk callouts.


6. Total Objects

- Limit: 50,000 objects retrieved in a transaction.

- Best Practice: Implement pagination or filtering when working with large data sets.


7. Email Invocations

- Limit: 5,000 emails sent in a day.

- Best Practice: Batch email processing and avoid sending unnecessary or duplicate emails.


8. Concurrent Apex

- Limit: 100 batch jobs in the Apex Flex Queue.

- Best Practice: Monitor and manage concurrent Apex jobs to prevent queuing issues.


9. Code Structure

- Best Practice: Maintain clean, well-organized code with clear comments and documentation to improve code readability and maintainability.


10. Error Handling

- Best Practice: Implement robust error-handling mechanisms to gracefully handle exceptions and log errors for debugging.


By keeping these fundamental governor limits in mind and adopting best practices, you can enhance the quality of your code and minimize the risk of encountering governor limit issues. With careful planning and efficient coding, you'll be well on your way to creating reliable, scalable, and high-performance Apex applications.

要查看或添加评论,请登录

社区洞察

其他会员也浏览了