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: info@areya.tech

Share:

Facebook
Twitter
Pinterest
LinkedIn
Areya Technologies

Areya Technologies

Trusted Technology Partner

Leave a Reply

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

Contents

On Key

Related Posts

Tutorial: Basic introduction to LWC

Tutorial: Basic introduction to LWC Lightning Web Components is open source, empowering you to explore the source code, customize the behavior for your needs, and build enterprise-ready web components on any platform, not just Salesforce. Lightning Web Components (LWCs) are a user interface (UI) framework that Salesforce Developers use to create customized pages and functions on the Salesforce platform. Lightning Web Components are seriously becoming the “big thing” for Salesforce Developers, especially for front-end development. Two programming models are now available for creating Lightning components: Lightning Web Components and the original form, Aura Components. Custom HTML elements known as “Lightning

Everything you need to know about SSO (Single Sign-On) and its Importance

Everything you need to know about SSO (Single Sign-On) and its Importance One of the more tedious jobs as a Salesforce admin is resetting users’ passwords. Even though there’s a button on the Salesforce login screen that says “Forgot your password”, some people don’t notice it. If only there were an easier way! Single Sign-On (SSO) is a simple idea: you will instantly be signed into all the other applications you require after signing into one system. You’ll have fewer passwords, fewer headaches, and less redundancy, which should free you up to focus on your original goals rather than getting

Basics: everything to know about Composite API and its advantages

Basics: everything to know about Composite API and its advantages A potential architectural answer that can bundle multiple calls into a single API request. Salesforce has been helping organizations handle the customer database for over 2 decades. It provides users with the right mix of process automation and personalization and tailor services to the specific requirements of the clients. Salesforce integration is the process of merging the data and the functionality of salesforce with another application to provide users with a single unified experience. It allows you to provide your team with the ideal platform features. We have the word

Beginners Guide to MuleSoft and the Anypoint Platform

Beginners Guide to MuleSoft and the Anypoint Platform MuleSoft can connect any system, application, data, and device to unleash the power of Customer 360. The combined power of MuleSoft, the #1 integration platform, and Salesforce, the #1 CRM, enables customers to accelerate digital transformation What is Mulesoft? 1. MuleSoft is a vendor that provides an integration platform to help businesses connect data, applications, and devices across on-premises and cloud computing environments. 2. MuleSoft unifies data to deliver a single view of the customer, automates business processes, and builds connected experiences. Each integration becomes a reusable building block using a modern

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