top of page

Apex Code Best Practices

In this post, we will talk about the best practices of Salesforce apex. Apex code is used to write custom business ideas and durability. As with any language, there are some basic principles and codes that will help you write code that is efficient, scalable. Let's talk about the best ways to design Apex Code.

Why we need the best practices of the Apex Code

Best practice recommended by Salesforce because apex operates in a densely populated area, the Apex operating time engine imposes strict limits to ensure that the apex code for runways does not use shared resources.

Let's talk about some examples of Salesforce apex code best practices.

Bulkify Apex Code

The term bulkifying Apex code refers to the concept of making sure the code properly handles more than one record at a time. When a batch of records initiates Apex, a single instance of that Apex code is executed, but it needs to handle all of the records in that given batch. Here is an example of a bad code.

Account account = Trigger.New[0];


In the above line, the code clearly accesses only the first record in the collection using the syntax Trigger.New [0]. Instead, the trigger should properly manage the entire Account collection using the collection.

for(Account account : trigger.New){
// add your logic here

Make reusability of Code

The best practice for the Apex Code is to write a code that can be reused in another application or module. This includes rendering the code generic so that it can be reused with minimal modifications.

Avoid nesting loops within loops

Nested loops should be avoided in Apex controllers as they may slow down page processing or may hit the governing limits for the page. Another easy way that gives a nice structure to make the inner loop a different function, or to reduce the use of loops completely.

We usually encounter code when we have two or three or more barriers generated that affect performance. An easy way to avoid nesting traps is to use Maps. For example, you can find or create a key for each second loop item and enter a key and value on the map.

Avoid DML & SOQL inside for loops

Do not place DML or SOQL statements (insert / update / delete / delete) within the loop.

for(Account account:{
 for(Contact contact:[select id from contact where accountId = :account.Id]){

Here is an example of placing a SOQL query without a loop.

Map<Id, Account> accMap=new Map<id, Account>([select id,name, (select id from contacts) from account where id in:trigger.newmap.keyset()]);

for(Account acc: accMap.values()){
      For(Contact con:acc.Contacts){ 

Use of the Limits Apex Methods

Use Apex Limits Methods to Avoid Striking SF Governor Limits. Most of us face the error of the governor limits in starting trigger/ classes/ test classes. The following are just a few of the governor's limitations: -

  • Too many DML rows 10001

  • Multiple SOQL queries: 101

  • Many query rows 50001.

Here are some tips on how to use Apex limit Apex methods

System.debug('Total No. of SOQL allowed in this Apex code: ' +  Limits.getLimitQueries());

Account account =[select id, name from Account where BillingCountry!=null  order by createdDate desc limit 1];

System.debug('1. No. of Queries used in this Apex code so far: ' + Limits.getQueries());

Now, using the above Limit methods we can look at how many SOQL queries we can extract from the current Apex Context

If(Limits.getLimitQueries() - Limits.getQueries()>0) {
  // Execute your SOQL Query here.

  • System class restrictions - use this to remove the debug message regarding each administrator limit - version 2

  • First: (eg Limits.getHeapSize ()) returns the amount of resources used in the current context.

  • Second: Contains the word limit (eg Limits.getLimitDmlStatements ()) and returns the total amount of resources available for that context.

  • Use Apex code directly to throw error messages before reaching the ruler limit.

  • If the end-user asks for Apex code that exceeds 50% of any governor's limit, you can specify the user in your organization to receive an additional event email notification.

Use Database Methods while doing DML operation

Apex transaction represents a set of tasks performed as a single unit. All DML transactions can be successfully completed, or in the event of a single operation, all transactions are undone and no data will be committed in the database. Apex gives you the ability to create a savepoint i.e., a point in an application that specifies the status of a website at that time.

By using the Database class method, you can specify or disable the partial record processing if errors are encountered.

Database.SaveResult[] accountResults = Database.Insert(accountsToBeInsert, false); // Using above code, we can work on failure records 
for(Database.SaveResult sr : accountResults) 
{ If(!sr.isSuccess()) {
 // add your logic here
 for(Database.Error err : sr.getErrors()) {

Querying Large Data Sets

SOQL queries can return 50,000 records. If we are working on large data sets that result in a bulk size limit, in that case the SOQL loop query should be used. Below are the examples.

Solution: Use the SOQL query to find the loop.

for( List<Account> accountList: [select id, name from Account where BillingCountry  LIKE%India%]) {
      // add your logic here.

Security and Sharing in Apex Code

One of the best ways of Apex Code is for developers to understand how to encrypt secure applications in the Salesforce Platform. Like how to enforce data security and how to prevent SOQL injection attacks on Apex.

Enforcing FLS Object and Permissions on Apex.

Apex does not enforce object-level and field-level permission automatically. Let's see how we can use CRUD and FLS in Apex.

  • Schema methods


  • Security.stripInaccessible()

  • Database operations in user mode (pilot)

Apex class sharing classes

Apex generally uses system context to mean that current user permissions and field-level security occur while the code is being used. Our Apex code should not disclose sensitive user information hidden in security and sharing settings. Therefore, Apex security and law enforcement sharing are very important. Let's see how we can force you to share on Apex by using the following clauses:

  • with sharing

  • without sharing

  • inherited sharing

Exception Handling in Apex Code

There are many ways to handle errors in your code, including using assertions like System.assert calls, or returning error codes or Boolean values, so why use exceptions? The advantage of using exceptions is that they simplify error handling.

DML statements return run-time exceptions if something went wrong in the database during the execution of the DML operations. Don’t forget to use Try catch blocks for exception handling.

          // Apex Code 
}Catch(Exception e){


This article covers many of the best Apex coding methods. We've discussed how to expand your code by managing all incoming records instead of just one. We also showed you how to avoid having SOQL queries inside the loop to avoid ruler restrictions. By following these principles, you are on the right path to success with

Apex code.

Follow us for more such posts...

bottom of page