Salesforce Apex Best Practices
Salesforce Apex is an object-oriented programming language used to write code that runs on the Salesforce platform. Salesforce is a multi-tenant platform as well, which means multiple tenants share the salesforce resources and to keep all of them in check for using the data resources efficiently, salesforce have some governor limits. Following best practices when writing Apex code can help ensure that your system is efficient, scalable and maintains governor limits.
Table of Contents
Here are some key best practices:
-
Bulkify Your Code to Handle Many Records at Once
In Salesforce, you often need to process bulk records at once. Bulkifying your code means writing it in a way that can handle multiple records at the same time. This helps avoid errors and makes sure everything runs smoothly, even when working with a large amount of data. For the purpose of bulkifying, you can leverage the asynchronous apex methods which are pre-customized to handle bulk records.
-
You Should Avoid Using DML/SOQL Inside Loops
Loop is a piece of code which is used to iterate over a collection or SObject until a certain condition is satisfied. When writing code, you might need to update/insert/delete (use DML Operations) or retrieve data (using SOQL queries). Doing this inside a loop (which repeats code) is a bad idea because these operations have governor limits on them. If done in a loop, they can quickly hit Salesforce limits, causing your code to fail. Instead, gather all the records you need, put them in a collection and perform the operation outside the loop to save resources.
-
Don’t Hardcode IDs
Hardcoding means writing specific record IDs directly into your code. This is risky because those IDs can change when you move your code to another environment (like from sandbox to production). Instead, use a reference that stays the same across environments, such as a name or unique code that doesn’t change and based on those references you can get the record Ids.
-
Use One Trigger Per SObject
In Salesforce, triggers are used to automatically run code when certain actions happen (like when a record is created or updated). Using multiple triggers for the same type of object (like an Account) can cause errors in runtime as there is no certain way to make sure that they run in the order you expect. Stick to one trigger per object to keep things simple and predictable.
-
Use Queries Efficiently in Loops
When you need to retrieve a large set of data, it’s better to place the query directly in your loop. This allows Salesforce to handle large sets of data more efficiently, breaking it up into smaller chunks so you don’t run into limits. When you put the query directly in the loop, it processes records in chunks internally, but it still counts as just one SOQL query. It does not run the query every time the loop iterates. Salesforce processes the entire result set once but breaks it into smaller manageable parts for efficiency.
Also Read – Unlocking the Power of AI with the Salesforce Einstein Suite
-
Test for Different Scenarios
When testing your code before the deployment to prod, don’t just aim for high test coverage, i.e., the percentage of code that gets tested for 75% coverage of code. Focus on testing for different scenarios and use cases. This way, you ensure your code works in all situations, not just the ones your tests cover.
-
Do Not Use Nested Loops
When writing the code, if you have loops within loops, your code can get complicated and hard to manage. Instead, break your code into smaller methods that are easier to understand, maintain and do not use multiple loops under loops.
-
Follow a Naming Convention
We have separate naming conventions for all coding languages. Using consistent names for your variables, methods, and classes makes your code easier to read and understand, especially for other developers. It’s up to your team to decide on the naming convention, but following one will make everyone’s job easier. The most popularly used naming convention is using camelCase. It is the practice of writing phrases without spaces or punctuation and with capitalized words.
-
Don’t Put Business Logic in Triggers
Triggers are not the best place to put all your business logic. Instead, use the trigger to call a separate class that handles this logic. This makes your code easier to test, maintain, and reuse. As we previously discussed, we should make only one trigger per object and if we put business logic in triggers, it will cause triggers to be very large, complex and difficult to understand. Instead, we can create separate handler classes for each business logic and call those classes from trigger.
-
Only Use Necessary Trigger Events
When writing a trigger, only include the events that are necessary. For example, if you only need the trigger to run when a record is created, don’t add events for updates or deletions.
-
Use Collections to Handle Data
Collections are the variables which can store data or records of different data types and SObjects. A collection is mainly of three types – list, set and map.
Instead of updating or querying records one by one, use collections (like lists or sets) to store multiple records and perform operations on them all at once. This is more efficient and helps avoid hitting limits.
-
Use Future Methods for Long-Running Tasks
Sometimes, you need to perform tasks that take time, like making an API call. For this purpose, salesforce has an out of the box solution. It has provided us with the asynchronous apex which can be used to run our apex operations in a most suitable way. There are different methods used under asynchronous apex – Queueable Apex, Batch Apex, Future Apex and Schedulable Apex.
You should use the Future method, which lets these tasks run in the background without holding up other operations. However, only use them when necessary, as they run when the system has free resources.
-
Avoid Recursion in Triggers
When a trigger causes another trigger to run, and that second trigger causes the first one to run again, you end up with a trigger loop (called recursion). This can make your code fail and throw errors. To avoid this, use a flag, like a static variable, to keep track of whether the trigger has already run, and stop it from running again unnecessarily.
-
Use Triggers as the Last Resort
Before writing a trigger, see if you can accomplish the same thing using Process Builder or Flow. These tools are often easier to maintain and don’t require any code, making your system simpler and more manageable.
You should always consider the trigger at last and try to achieve the desired functionality using admin automation tools first.
Conclusion
Following best practices in Salesforce, especially when working with Apex code, ensures that your system is both scalable and efficient. By following all these best practices, you can avoid hitting Salesforce’s governor limits and improve performance. Simple adjustments like using collections and avoiding hard coded IDs help make your code more manageable and adaptable. Ultimately, these best practices make it easier to maintain your code and ensure smooth operations as your data and processes grow.
Upgrade Your Skills – Join Salesforce Classes in Pune