Let’s take a look at some key best practices you should follow as a Salesforce Developer who writes apex code on a daily basis.
- No Hardcoded IDs:
Never hardcode IDs as your functionality might work in the current environment but won’t if you promote it to other orgs. IDs are unique to an org but not across orgs. So be mindful of not hardcoding values in any part of the code. Query it from the Schema, use Labels to store some static value, but do not hardcode IDs.
- Code Bulkification:
Your code should be able to handle more than one record at a time. Your code should be scalable so that governor limits can be avoided.
- Avoid DML or SOQL inside loops:
Salesforce provides a fixed limit of DML and other requests that can be made in a single transaction. If we add a SOQL within a loop, it is bound to hit the governor limit sooner or later. So, it’s always better to avoid SOQLs and DML statements within loops.
- Use Efficient Queries:
Query records with the best filters applied so that you are not unnecessarily query more records than needed. This plays a very important role in speed optimisation of your code. Also, ensure you query only the fields you need. Do not unnecessarily query fields you are not using in the code.
- Use Collections:
Instead of writing nested for loops and creating record sets over and over again, try and associate your records via Map and use Map functions to fetch values in loops. It reduces the time complexity and improves code scalability.
- One Trigger Per Object:
If you have multiple triggers written for a single object, you wouldn’t know for sure, which trigger would be initiated first. That leads to flow inconsistency. Also, you might be querying large chunk of same data in both triggers which is near to irrelevant. So, ensure, you have a single trigger per object which handles all events in a streamlined fashion.
- Trigger Framework:
A good trigger framework ensures the trigger routes all its work to a handler/helper file that takes care of the business functionality. This helps in keeping the trigger clean and enhances code readability and maintenance. Bonus: Add event based checks on your trigger and call helper methods accordingly.
- Enhanced For Loops:
Instead of querying large data sets, it’s always better to use enhanced for loop. Enhanced For loops operate with a chunk of 200 records at a time which saves your code from running into RunTime Exception.
- Use Limits:
Methods like getQueries, getDMLRows, getDMLStatements can help us add checks at places where we are doubtful that the code might throw a governor limit error.
- Future Methods:
Use asynchronous apex like future methods to move any code that can be done in the background to improve time complexity. But make sure, you don’t overuse it as there are limits to asynchronous apex as well.