What are some Salesforce best practices

There are Salesforce best practices that you need to know to boost productivity, increase functionality, and reduce errors.

  • Published 25 Nov 2022
  • 13 mins read
What are some Salesforce best practices
Table of contents

Hutte Expert Panel

Here are the experts we collaborated with to bring you unique insights.


Article Summary Box

Article Highlights

  • The article emphasizes the importance of following best practices in Salesforce to enhance platform efficiency, such as modularizing code, bulkifying Apex code, and avoiding hard-coded IDs.
  • It discusses strategies for managing Apex code, including using maps to avoid nested loops, processing tasks in batches, and handling exceptions properly to improve Salesforce application performance.
  • The article outlines the significance of adhering to security measures and naming conventions in Apex code to ensure secure and maintainable Salesforce applications. It also touches on the concept of using storable actions in Lightning components for better performance.

If you consider hiking as an example, the best practices that guides will tell you to follow are as follows:

  • Find a knowledgeable hiking partner or buddy.
  • Be physically prepared for the challenge.
  • Be prepared ahead of time when it comes to the weather.
  • If you are climbing to high depths, you need to have altitude training under your belt.
  • Have the right tools and equipment to get you from point ‘A’ to point ‘B.’

Like hiking, being a Salesforce expert requires you to put in the necessary work and best practices to make the most of the platform. According to Salesforce, CRMs like theirs can boost business revenue by 41%.

That’s why you need to be well-versed in Salesforce best practices, whether you're a developer or an administrator. Let’s have a look at what some of them are.

Modularize your code

When composing Apex code for an organization, segments, and bits of it are likely rehashed throughout the codebase. Users might be enticed to reorder these techniques or code blocks into various classes, but this can quickly make the Apex code unmanageable.

Think about a time when you've composed a valuable method to assist with helping to construct dynamic SOQL queries.

Another necessity comes up that you realize will profit from this management strategy, so you duplicate it into your new class, and it ultimately functions well. After a few weeks, a fairly serious bug has been tracked down in the underlying shopper of your functionality, which you extensively fix.

🐜
You want to apply a fix to the next class, so you added it. This rapidly becomes unmanageable, as the need might arise to refresh each spot it's been replicated to. Each time, it presents a more severe risk of additional bugs.

The best practice for any business process is to put these reusable bits of code into their independent classes. This can hugely reduce the intricacy of your code (which requires these techniques). And when a bug is tracked down in your functionality, it can be fixed.

Using (unlocked) packages helps to understand and manage dependencies leading to a better architecture. Having versioned and documented changes over time makes projects more transparent and successful.

Matthias Rolke

Freelance DevOps Consultant
Salesforce

Source: Hutte

Bulkification of your code

Bulkification is a management plan for your Apex code in Salesforce. It’s the most common way of making your code ready to deal with various existing and incoming records all at once.

♻️
This is primarily valid for Apex triggers, where up to 200 records could disappear immediately. If your Apex code hasn't been composed to consider this possibility, it can be problematic throughout the development lifecycle.

For that reason, as Salesforce recommends, you should ‘bulkify’ all your Apex classes to work on your organization's performance in addition to the triggers. Apex code also has governor limits and, for instance, a trigger framework that can deal with up to 200 records immediately through custom settings.

However, it is expected that you import considerably more with Data Loader. This is why you must be cautious when constructing your trigger.

Stay Away From Hard-Coded IDs

As you create your Salesforce solutions, you frequently need to reference a part or text, whether it is a record scope type, custom permission set, user, or queue. The fastest way is to reference the Salesforce ID. However, is it the most effective way?

A best innovation practice is not to reference IDs, text straightforwardly, or ‘hard code’ them. This best practice applies to the automation tool's admin side, including entire Process Builders, Flows, Workflows, and validation rules. You shouldn't hard code IDs or text in your formulas and validation rules.

The following are two reasons why you shouldn't hard code:

  • The code element you want to reference doesn't exist in production environments – you just make it for the arrangement you're building. That code will ultimately have another ID that only exists in that specific sandbox. Each time a specific code is made, consequently, an alternate Salesforce ID will be created.
  • Suppose you want to investigate or improve a current arrangement, and it references a hard-coded ID. In that case, you can only, with significant effort, determine what that part is without looking into the ID. This is because the Salesforce ID isn't self-portraying.

One trigger per sObject

The Salesforce platform does not have a method for ensuring a request for the execution of triggers on a similar single object. Having just a single trigger empowers us to control the progression of execution, which in turn takes into consideration simple management.

However, an irregular trigger request likewise introduces randomness into the code. This uncertainty makes it harder for developers and admins to troubleshoot and foster code.

Avoiding nested for loops

Nested for loops should be kept away from Apex controllers since they might dial back the handling of the page or raise a ruckus around governor limits for the page.

People frequently experience Apex code, where they have a few or more nested loops influencing execution.

A basic approach to keeping away from nested loops is utilizing maps. For instance, you can find or make a key for everything in the subsequent loop and put the key and the worth into the map.

Process similar tasks in batches

While working with most information records, it is the best practice to deal with and process comparative records arrangements simultaneously with a single API demand.

Doing so will bring about:

  • Limited API demands.
  • Saving you from a governor limit.
  • Further developed API execution.
  • Better transmission capacity utilization.
  • Moving computing burdens to a superior cloud environment.
💭
When a group of records needs to be refreshed through the Salesforce API, the Apex code trigger controller will be summoned. The cluster of records is then handled under a similar Apex code as a bulk.

Try Not To Utilize A DML Or SOQL Query Inside A Loop

Avoid putting SOQL or DML statements inside a loop. When these tasks are set inside a loop, database tasks are triggered per loop, making arriving at SFDC governor limits extremely simple.

The best way is to put every one of the sObject elements that require an insert, update, or deletion in a list, as they will then perform the DML routine operations.

Another method for reducing DML statements is using asynchronous procedures, like future techniques. Essentially, you offload the DML from the ongoing exchange, making it much quicker when triggering per object.

For SOQL, if you want queried results, get every record using a single query and repeat it over the result set. This way, you can avoid using SOQL queries or DML operations inside a loop.

Exception handling in Apex code

DML statements encounter issues if something turns out poorly in the database during the execution of the DML activities. Moreover, remember to utilize ‘try-catch’ blocks for exceptional cases.

With Apex, you can compose scalable code that answers explicit special exceptions. Some examples of exceptions in Salesforce Apex are “Null Pointer Exception,” “DML Exception,” and “Query Exception."

Utilizing an async process

Apex is part of an automation strategy when it arranges higher governor limits. For instance, the quantity of SOQL queries is multiplied from 100 to 200 while utilizing separate calls.

The all-out stack size and maximum CPU time are comparably bigger for these calls.

Security and sharing in Apex code

One of the Apex code best practices is for developers to understand that they need to code secure applications on the Salesforce platform. For example, how can core security functions be upheld, and SOQL injection ‘fights’ in Apex be prevented?

When authorizing objects and FLS permissions in Apex, Apex doesn't authorize object-level and field-level authorizations naturally.

Regarding sharing clauses for Apex classes, they run in a framework setting that implies the current user authorizations and field-level security assume a position during code execution.

🔒
Therefore, the Apex code shouldn't reveal delicate information to end users; this information is covered up by security and sharing settings. Thus, Apex security is generally critical to upholding optimal sharing guidelines.

Naming conventions

Regarding Apex code, you need to follow a legitimate naming convention. Salesforce naming conventions are standard when choosing what to call your identifiers, such as class, variable, consistency, technique, and so on.

Utilize storable action

The Lightning component shows reserved results instead of making a quick server trip. The Lightning component will make a server (Apex code) store and strengthen it.

This is extremely valuable for devices that have slow web associations. For example, if you are a Facebook or Google News client, you would usefully connect with it.

When you open these applications, they show the past feed. If there are news feeds, you can choose to bring back the view or strengthen it.

On the client-side regulator of the Lightning component, you can simply mark the activity as ‘storable’ using this code: “action.setStorable().”

Test multiple scenarios in Salesforce Apex code

Salesforce tells its users they should not have less than 75% code coverage when they want to put Apex code into Salesforce. Remember that taking care of countless lines by tests is a decent objective, but it doesn't tell the entire story regarding testing.

Composing tests just to accomplish the code inclusion requirement shows that your code has been run. When creating your various test data sets, you should cover different use cases for your code. This guarantees that you're covering the situations in which the code is being run.

You do this by composing numerous test techniques, some of which might try similar strategies and not produce extra covered lines—each runs the code under an alternate situation.

👨‍🔬
For instance, this could cover a positive case and a negative case in an Apex trigger. After running tests, you must approve that the code has played out its expected activity.

Tests like these offer undeniably more benefits than just composing tests for code coverages. They can be an early warning metric for issues emerging when an administrator adds some new usefulness or alternate code. Testing for these situations guarantees you are aware of the potential issues and how to fix them.

Declare the sharing model

When you start composing a fresh new class, perhaps the earliest thing you should do is declare your sharing model. Assuming you require your Apex code to sidestep record access, you should continuously declare without sharing.

By announcing your sharing model, you can show the purpose to anyone who chips away at your code. This also allows them to determine what's happening inside the code effectively.

You have brushed up on your best practices - now it's time to put your best Salesforce foot forward

Companies and development teams that focus on becoming customer-centric are stepping up to implement Salesforce to benefit from its CRM capabilities. Salesforce helps organizations provide a consistent, holistic customer experience (and developer experience) across channels, with a 360-degree level of awareness of their clients and an understanding of current trends.

You're always traveling down a never-ending path full of product updates, new use case scenarios, and increasing business values.

As you go through life, you’ll encounter challenges and changes. Still, you can overcome them by using an adaptable Salesforce approach and a link to the best Salesforce knowledge and best practices available.

Once you're connected to the right people online and know where to look for good resources, you'll be better equipped as you learn how to leverage Salesforce to create better products, customer experiences, and internal workflows.

🧐
With Salesforce, you can use business logic to configure it to suit your business needs to some degree. However, if at all, it's impossible to do so with configuration alone. Customizations or custom applications may be required instead.

As a developer, you want to improve things through an improved user experience and user interface. You and your team can be at the top of your game by keeping your business processes simple and consistent and continuously following best practices.

If done correctly, Salesforce development can achieve a business's objectives by helping companies use features that improve their performance and efficiency. Following Salesforce, best practices can help:

  • Create user-friendly apps and app alerts with industry-related features.
  • Build features and a block of code to handle user queries, feedback, and delivery requests.
  • Create predictive reports by adding analytic capabilities to your site.
  • Create or customize different mobile and web applications for specific business needs.

Document
Sign up for Hutte



Last updated: 13 Jun 2024