Apex Best Practices

By in
104
Apex Best Practices

Apex is a customized solution on the Salesforce platform. As a result, best practices need to be followed when creating and testing apex in Salesforce since it’s something that’s being built by the developer and not by Salesforce.

Salesforce Apex Text Best Practices
Image Source: Salesforce Apex Developer Guide

 

Apex Best Practices

Some of the standard best practices of Apex, in general, are as follows.

  1. Always ensure that the apex class has an appropriate sharing set. For example, With Sharing or Without Sharing
  2. Naming conventions and indentations should be followed and consistent throughout the instance.
  3. Always avoid nested for loops.
    • This can be done by using Map<>
    • Instead of iterating over all the items inner list again and again for every single outer list item, it’s best to create a Map<> that would take care of nested For
  4. No DML inside For Loop
    • There shouldn’t be any DML in For Loop as it would cause the DML limit to hit.
  5. No SOQL/SOSL inside For Loop
    • There shouldn’t be any SOQL statement inside for loop as you can only have 100 queries per transaction
  6. No hard-coded Strings
    • Every hard-coded String should be stored in Custom Settings or Custom Metadata
    • Hard coding has a serious problem that if at any point the code needs to work with some other parameter or data, then the current code has to be rewritten and then deployed again.
    • We can avoid this by using custom settings that help to keep the code hard coded stuff customised.
  7. Preference to custom metadata
    • As it can be deployed, you should give more preference to Custom Metadata than Custom Settings.
    • However the custom settings need to be inserted pre deployment every time.
  8. Modularise your code
    • Code should be readable and try to use Apex Enterprise patterns
  9. The apex test should be covering 100% of the Apex Code.
    • Test all possible scenarios including Bulk.

 

Conclusion

In this way, you must use best practices while developing apex classes. This is to ensure that the code is running in an optimized way.

 

To learn more about Apex and Best Practices, check out my related blogs below!

 

Additional Resources

Cover Photo by Jen Theodore on Unsplash

Leave a reply

Your email address will not be published. Required fields are marked *