The 15 Best Practices for Apex Code Exchange

 

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?

● The Apex runtime engine strictly enforces some Salesforce Governor limits to ensure that the runways apex code does not monopolize shared resources.
● Simplicity means you don’t do what you can do in 5 lines with 10.
● Readability means what it says: that others can read your code.
● Design means you take time to plan your program before you
build it.
● Efficiency means your program is fast and economical.

1.Bulk-ify Your Code

● Making your code capable of effectively handling several records at once is the process of bulk-ifying 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 behavior if your code still needs to be written to compensate for that.
● Additionally, we can bulkify our code to lessen 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/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 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 Apex Trigger,, you should follow the 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 contexts. er object.

8. Security and sharing in Apex code

●  One of the Apex Code best practice is developers must understand to code secure applications on the Salesforce Platform.
●  How to enforce data security and prevent SOQL injection attacks in Apex.
●  Enforcing Object & 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 always to 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 & 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]

Share:

Facebook
Twitter
Pinterest
LinkedIn
Areya Technologies

Areya Technologies

Trusted Technology Partner

Leave a Reply

Your email address will not be published.

Contents

On Key

Related Posts

Salesforce: Einstein Search

Salesforce: Einstein Search “Personal, Natural & Actionable” If you’re one of the 4.5 billion people who use the internet today, you probably use a search

San Francisco Headquarters

One Bay Plaza, 1350 Old Bayshore Hwy,#520 Burlingame, CA 94010 ​

Bengaluru Office

IndiQube Edge 4th floor Bellandur, Bengaluru, Karnataka 560103

Pune Office

OYO Workspaces India Pvt. Ltd. Above Vijay Sales, 2nd floor, Pride Purple Accord, Baner road, Baner, Pune - 411045