Enhance Your Apex Code Unit | Adopt Salesforce Best Practices

In this blog post, we will explore Apex best practices. Apex code is employed for crafting custom business logic, and as with any programming language, adhering to syntax and best practices is crucial for creating clean and efficient code. Today, we’ll delve into the best practices specific to Salesforce Apex.

Let’s explore the reasons behind the importance of best practices.

Salesforce recommends best practices for Apex because it operates in a highly populated environment. The Apex runtime engine enforces stringent limits to ensure that Apex code execution doesn’t monopolize shared resources.

Optimize Apex Code for Bulk Operations

Bulkifying in this context refers to processing multiple records simultaneously. When dealing with multiple records, it’s important to handle scenarios where code execution might not occur, such as nullification. Here’s an example of bulk processing in action.

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

Enhance Code Reusability

As indicated in that statement, it’s crucial to create helper classes and define methods within them. When we require the functionality of a particular method, we can simply call the corresponding class and utilize that method. This approach is instrumental in making our code reusable.

Minimize Nesting of Loops


It’s advisable to steer clear of nested loops in Apex controllers as they can potentially slow down page processing or reach the governing limits for the page. An effective strategy is to structure the code by separating the inner loop into a separate function or minimizing the reliance on loops altogether.

When faced with code that contains multiple layers of loops impacting performance, a practical approach is to utilize Maps. For instance, you can assign or generate a unique key for each item in the second loop and then store the key-value pairs in a map.

Minimize DML and SOQL Queries Within For Loops

As we’re familiar with the concept of governor limits, it’s important to note that DML operations have specific limits. For example, you can perform a maximum of 150 DML operations. If a loop runs more than 150 times, it can cause our code to break.

Here’s an example illustrating best practices.

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){}
}

Leverage Database Methods for DML Operations


Essentially, both Database methods and DML operations function similarly in terms of their operations. However, Database methods offer greater flexibility compared to DML operations.

One key distinction is that Database methods allow for partial operations, which is not a feature of DML operations. In DML operations, we cannot retrieve lists of successful and failed records, whereas Database methods provide this functionality.

Here’s an example illustrating how Database methods should be used:

Database.saveResult[] accuntResult=
Database.Insert(accountsToBeInsert,false);
work on failure records
for(Database.SaveResult sr:accountResults)
{
    If(!sr,isSuccess()){
        //add ypur logic here
        for(Database.Error err:sr.detErrors()){}
    }
}

Handling Large Data Sets Using Queries

In Salesforce, a single SOQL query can retrieve up to 50,000 records. When dealing with large data sets that exceed this limit, it’s imperative to utilize SOQL queries effectively.

Here’s an example demonstrating the proper use of SOQL queries for large data sets.

for(List<Account> accountList:[select Id,name from Account where
BillingCountry Like '%India%']){
    //add your logic here
}