In Apex, there’s quite a few constraints that are strictly enforced because the platform is a shared multitenant environment. Quite a few of the limits result in runtime exceptions that can’t be handled.
For those familiar with Salesforce, it’s no secret that there’s a lot of limits. For example, there’s limits around the ViewState which were pretty painful to work around.
One of the first limits, I believe all new Salesforce developers hit is the limit for a maximum of SOQL queries that can be done.
Don’t do Queries in Loops
Whenever possible, queries should never be done insider loops because it will cause your code to execute slower and hit governor limits.
To avoid doing this, it’s usually easiest to move the query outside of the loop and have it query all of the necessary data.
Evaluate your Architecture
Hitting errors like the 101 query error often are the result of functionality not being isolated well enough. Take the time and really understand the Salesforce Order of Execution.
Usually it makes sense to avoid running triggers twice, but you also shouldn’t blindly stop them from processing twice. Where possible, it usually makes sense to combine triggers and move towards tiered systems. I’ve put together a blog post of Apex Trigger Practices which can really help reduce SOQL Query Limits.
If you can use Describes instead of SOQL, you should really consider doing that instead of querying. For example, there’s no need to do a query for the RecordType when you can instead do a Describe.
Caching can be done in quite a few different ways. For example, you could use static variables or take advantage of the platform cache.
I recommend using static variables or custom settings when you know tbe data is unlikely to change much if/ever.
Use a Different Context
Batch Jobs can be a really good way of doing a lot of querying and processing. For jobs that are doing data transformations or billing processes that only need to happen a few times a day, the batch or scheduled apex can work wonders.
If your processing is going to be very time consuming, it might even make sense to evaluate one of the Salesforce APIs and use that instead of doing it within Salesforce. I’ve put together a blog post regarding the various Salesforce APIs.
Avoid Process Builder
Process Builder is a really great declarative tool for small orgs that don’t do a lot of advanced apex.
Unfortunately, it doesn’t scale very well because its not bulkified. I personally avoid using it on the Account, Opportunity, lead or contact because of this.
Author: Brian Cline
Also published on Medium.