Advanced Apex Training: Apex Best Practices

This article dives into what we, developers at Solunus, recently learned as we attended ‘Apex Best Practices’ training session at our Global Delivery Center, Hyderabad. This is one of many advanced topics the company organized for all Salesforce developers as part of the continuous improvement and learning. I took some time to write this blog to reflect on all the things I learned (with some of code samples) from our Senior Architect and I hope this will help other developers too. For more details, please watch this awesome video ‘Winter ’16 Release – Overview & Highlights‘.
Follow along, as I show you all the guidelines you should consider when writing code for your next Salesforce applications.
Governor Limits
Why governor limits?
Force.com is built on a multi-tenant Architecture. In order to ensure that Apex code of a single tenant does not consume significant amount of shared resources on Force.com platform and to ensure every tenant gets equal share of the platform resources.
Per-transaction Apex Limits
Total # of SOQL Queries: 100 (Sync) | 200 (Async) Total # of records retrieved: 50K Total # of DML statements: 150 Total # of records processed by DML: 10K Total heap size: 6MB (Sync) | 12MB (Async) Maximum SOQL query runtime before Salesforce cancels the transaction: 120 seconds
SOQL
Avoid writing non-selective queries except during batch processing. Avoid using only negative operators (!=)
Use Primary Keys, Foreign Keys, CreatedDate, LastModifiedDate, External ID or Unique Fields in query filters.
Example for Batch Processing : Mass Delete of Records
Bad Query (When record count exceeds 100K)
SELECT ID, NAME FROM ACCOUNT
SELECT ID, NAME FROM ACCOUNT WHERE NAME != ‘ ‘
Good Queries
SELECT ID, NAME FROM ACCOUNT LIMIT 5
SELECT ID, NAME FROM ACCOUNT WHERE ID IN :IDS (Only when ID list is small)
SELECT ID, NAME FROM ACCOUNT WHERE NAME != ‘’ AND OWNERID IN :OID
What happens if I dont write selective queries?
Salesforce could throw a runtime error like this:
System.QueryException: Non-selective query against large object type (more than 100k rows). Consider an indexed filter or contact salesforce.com about custom indexing