Areya

areya

If you’ve worked on the Salesforce platform for more than a few minutes, you’ve likely heard the term “best practice” mentioned, whether you’re a developer or an administrator. But what does it mean?

It is a term used to describe a strategy or approach frequently considered superior to other techniques, to the point that doing anything else will typically be met with raised eyebrows! This article will look at some Salesforce Apex best practices and explain why they’re best. 

Why do we need Apex Coding Best Practices?

A few scenarios that show how Salesforce Genie makes the customer experience so much better:

●  At 3 p.m., you report the theft of your credit card after losing it. Your card is being used to purchase something at 3:05, but it is instantly declined because the merchant uses Commerce Cloud Genie and gets instant alerts.

●  You contact customer support to report a product-related issue. This results in an automatic response that halts all marketing and sales interactions with you until your case has been addressed because the company uses Service Cloud Genie. You, therefore, are immune from routinely irritating interactions that turn away clients, like receiving an email pitch to purchase the specific product you are experiencing a problem with.

●  A personalized offer you’re viewing on a website changes immediately due to a marketing email you just clicked on. Owing to the business’s use of Marketing Cloud Genie, that offer is now more relevant to you than you would have otherwise considered, compelling you to proceed with the purchase.

●  You need urgent medical attention. Your real-time patient data enables your healthcare professional to provide proactive guidance and care recommendations where milliseconds matter.

 

1.Bulk-ify Your Code

● Making your code capable of effectively handling several records at once is the process of bulkifying it. This is especially true for triggers, which allow the simultaneous processing of up to 200 records, like those from a data load.

● Errors may be thrown, or even worse, unexpected behaviour may occur if your code still needs to be written to compensate for that.

● Additionally, we can bulkify our code to reduce the number of
expensive operations, such as queries, to help a piece of code
perform better.

● If you know, there won’t be many records in an invocation, such as when using an API or an Apex action invoked through a
screen flow, you can avoid bulkifying your code.

● However, given how simple it is to bulkify the majority of code,
You should develop the practice of doing so anyway!

2.Avoid SOQL & DML inside for Loop

●  You should query sets of records based on specific circumstances or insert or update several records simultaneously.

●  What might happen if you query or do DML operations on these records while inside your for loop? Well, a good deal…

●  Some of the most expensive activities we can carry out with Salesforce Apex include SOQL and DML, and both have stringent governor restrictions. Therefore, putting them into a loop is a prescription for catastrophe since, especially when triggers are present, we can quickly and unconsciously reach these limitations!

●  When using DML statements, we can move those statements outside the loop and add the records we want to manipulate into a list, then execute the DML statement on that list.
This is the finest and safest course of action in almost all circumstances.

3. SOQL Best Practices in Apex code

4. Avoid hard coding

● When we migrate our code into production, hardcoded IDs may initially function well and without incident, but they will no longer refer to the correct record.

●  This is remarkably accurate for Record Types developed in a Sandbox before being transferred to Production.

●  Consider the alternative: if we build a sandbox from production, our hard-coded IDs no longer refer to the appropriate entries.

●  Suppose the ID we want to utilize is tied to a particular record. In that case, we can store it as custom metadata and obtain the value at runtime, allowing us to update it as needed to accommodate different settings or requirements.

●  The only situation in which we don’t need to use one of the two methods described above is when we are explicitly referring to the Master Record Type.

5. Use database methods while doing DML operation

●  An apex transaction represents a set of operations executed as a single unit.

●  All DML operations in a transaction either complete successfully or if an error occurs in one operation, the entire transaction is rolled back and no data is committed to the database.

●  Apex gives us the ability to generate a savepoint.

●  Using the database class method, we can specify whether or not to allow for partial record processing if errors occur.

6. Exception handling in apex code & Use Asynchronous apex

●  DML statements will return run-time exceptions if something goes wrong in the database during the execution of the DML operations.

●  Don’t forget to use Try catch blocks for exception handling. With apex, you can write code that responds to specific exceptions.

● Apex, written within an asynchronous method, gets its own independent set of higher governor limits.

● For example, the number of SOQL queries doubles from 100 to 200 when using asynchronous calls.

● The total heap size and maximum CPU time are similarly larger for asynchronous calls.

7. Write one trigger per object per event

●  Apex triggers within Salesforce are designed to help you automate specific tasks.

●  While writing an Apex trigger, you should follow best practice and create one trigger per object.

●  A single Apex trigger is all you need for one particular object.

●  If you develop multiple triggers for a single object, you cannot control the execution order if those triggers run in the same context. er, object.

8. Security and sharing in Apex code

●  One of the Apex Code best practice is that developers must understand how to code secure applications on the Salesforce Platform.

●  How to enforce data security and prevent SOQL injection attacks in Apex

●  Enforcing Object and FLS Permissions in Apex: Apex doesn’t enforce object-level and field-level permissions by default. Schema methods, b). WITH security enforced, c). Security.stripinaccessible(). Database operations in user mode (pilot)

●  Sharing Clauses for Apex Classes: Our Apex code should not expose sensitive data to users, which is hidden via a. security and sharing settings, b.

9. Make reusability of Apex code

●  Break methods into multiple minor ways, making your code more modular and easier to read and maintain.

●  An essential best practice with Apex Code is to always write scalable and reusable code so it can be reused in another functionality or module.

●  This entails making code generic so it can be reused with minimum modification.

10. Code coverage

●  Unit texts are the test the developers perform to ensure that functionality is working as expected, considering both positive & Negative tests.

●  Not focus on the percentage of code coverage

●  Bulk Records

●  Positive & Negative testing.

●  Restricted User testing.

●  One Assert Statement per method

●  Should not use @isTest|seeA||Data=true}

11. Return early pattern

●Return early is the way of writing functions or methods so that the expected positive result is returned at the end of the function and the rest of the code terminates the execution.

12. Avoid nesting loops with loops

●  Nested loops should be avoided in Apex controllers because they may slow down the page’s processing or hit the page’s governing limits.

●  One easy way, which gives some excellent structure to the code, is to make the inner loop a separate function or minimize using loops altogether.

13. Don’t mix apex, process builders, workflow rules, and record-triggered flows

●  You should choose one automation tool per object.
●  One of the many inevitable scenarios of older orgs is to have Apex triggers mixed in with Auto launched flows/processes or, more recently, Process Builders mixed in with Record-Triggered flows.
●  Poor performance.
●  Unexpected results due to the inability to control the order of operations in the ‘stack’Increase in technical debt with admins/devs not collaborating.
●  Documentation debt

14. Naming conventions

15. Set up code review, Checklist, and code review process

Every developer needs to follow best practices. Understanding the why and the what can help us become better developers by enabling us to make more educated decisions regarding the potential effects of our choices, both in the immediate and long term.

We’d love to hear from you all in the comments on the best practices you believe are most crucial and why, as the aforementioned list is by no means exhaustive. Coding is fun!

Let us know your thoughts!

For more blogs: https://areya.tech/blogs/

To know more: connect with us today!
Contact: [email protected]

Contents

Related Content

Don’t Settle for Average Salesforce Performance.

Get a Free Health Check – Identify areas for improvement and optimize your Salesforce instance with Areya.