top of page

9 Dos & 7 DON'TS - Apex Best Practices

Actualizado: 4 ago 2022


In my opinion, one of the great things about the Salesforce Multitenant Structure is that it encourages you to write very efficient code from the beginning.

Keep in mind that Apex, just like any other programming language, has many possible ways to do the same thing, but some of them are more efficient than others. And some are definitely on the path to hitting the long feared Governor Limits (Salesforce version of the Blue Screen of Death).

Whether you are an experienced Salesforce Developer or you are just getting started, keep in mind this set of Dos and Don’ts that will save you tons of development work.


Dos:


Always try to do the following so you can ensure the best possible experience for your users.


Please, DO:


1. Is your logic simple? Maybe you don't need an Apex Trigger.


Salesforce will always encourage you to use its declarative tools (like Flows). Why? Because they have been already super tested and they use the Salesforce resources efficiently. Also, you do not need to write unit tests for your developments here (HUGE TIME-SAVING!).


If you know that the business logic you need to implement is highly complex with deep calculations or needs special user interfaces, then consider using Apex Code.


Check this great resource about declarative vs imperative programming.


2. Use one trigger per object.


Since you cannot ensure the order of execution of various Triggers for the same object, having one Trigger per object and dispatching the triggered records from there is the best way to go. You can control this based on whether it is an update, insert, before, or after and some conditional logic.


3. Keep the logic outside of triggers.


An sObject Trigger file should only contain small logic to dispatch the updated, inserted, deleted, or undeleted records into helper methods. Try to keep a Trigger as simple as possible and avoid making calculations here!


4. Use Maps to find your way.


For inside a For? We don't use that here! A Map is a very efficient data type that can help you simplify your code (and improve its time complexity) using key-value pairs. Check this great article that shows an example of usage.


5. Use relationships in SOQL to minimize queries.


Whether you need child-related records or parent record values, take advantage of the SOQL. You don't need to understand complex inner left or right joins. You only need to understand the relationship between two or more objects and that's it.


6. Write positive and negative test cases.


Knowing what your code should do and what it should not do is a must. So, why not write those use cases in your unit tests? It will make your development bulletproof.


7. Thrive for 100% code coverage in unit tests.


This one is related to your previous one. When you write positive and negative test cases, you get the chance to achieve a higher code coverage percentage. Always aim to get a 100% coverage percentage.


8. Use asynchronous logic when possible.


There are some processes that need to run on the spot, right in front of your user after clicking a button or updating a record. If your user does not require records creation right away, or you need to process a large set of data, use asynchronous code. You'll thank me later.


9. Use simple and reusable code, always!


And last but not least in this list of Dos! Has it happened to you that you write code and after a few weeks, you cannot understand the logic behind it? Use simple and reusable code to avoid this. It does not only applies to Apex, it applies to programming in general. See the KISS principle.



Don’ts:


If you made it to this point, congratulations, now you know some great things you can do to make your code run faster and more efficiently. But, with great power comes greater responsibility.


Avoid doing any of the following at all costs, since they threaten the integrity of your code, and potentially will make you users complain about features that simply do not work.


Please, seriously, DO NOT (can not emphasize this more):


1. Put queries in loops.


Big DO NOT! – The system executes a query with every loop iteration, and you only have 100 queries per synchronous transaction (200 per asynchronous transaction). If you execute a loop with an array of 101 records: Houston, we have a problem!

Even though you are sure you will not process a batch of more than 100 records inside a loop, putting a query inside a loop is a big NO!


2. Put DML in loops.


Another big DO NOT! – Same logic as putting queries in a loop. Create a list, add records to a list inside a loop and then insert the list out of the loop. Trust me.


3. Use dummy code coverage.


You are almost done; you need only 1% or 2% extra coverage to reach that 75% needed to deploy your code into production. You are already burned out and do not want to think more about code for the day, and you decide to use dummy code like ‘i++;’ 20 times to achieve this and go home… NOOOOO! This is a terrible practice. Take a break, get something to eat (or get some rest), and thrive to reach the best coverage possible without cheating the system.


4. Use existing data for testing.


Sandbox data and production data are not the same. Better to have your own set of test data, unchangeable across the Salesforce universe, right inside your test class. What if your production data and sandbox data is different? Your test class is probably going to fail (miserably).


5. Hard code IDs.


As said previously, sandbox data and production data are not the same. Even though you may have similar records on both sides, IDs are always different. This applies for Record Types as well.


6. Introduce extra logic to avoid making callouts.


Using the Test.isRunningTest() Boolean inside an IF-ELSE statement is not a good practice and will prevent you from obtaining your 100% code coverage. Use HttpMock and WebserviceMock interfaces instead.


7. Use synchronous processing on large data sets.


My personal recommendation: If you are planning to update more than 2.000 records at once, you should use a Batch Job or any other Asynchronous way of processing them; otherwise, you are prompt to hit the Salesforce Governor Limits in a blink of an eye.



And that's it. What do you think? Did you know those Dos & Don'ts? Are there any missing? Let me know in the commentaries!



Additional Resources:


Commentaires


  • linkedin

©2022 por Sergio Pedraza J.

bottom of page