Architects / Admins / Consultants

5 Important Best Practices for Optimizing Salesforce

By Patrick Fendt

Branded content with Platform Technologies

It is Fall 2024, and everyone is excited about AI and Data Cloud (as they should be). However, I want to provide an updated summary of some key Salesforce best practices (and hopefully some wisdom herein) given my 11 years of Salesforce architecture, consulting, and development experience with large and medium-sized customers.

In this article, I am going to highlight five key technical best practices that will help minimize technical debt and improve the value you get out of your CRM – including how (and when) to use Flow and Apex.

1. Invest in Non-Functional Requirements

First, let’s talk about one of my pet peeves topics: non-functional requirements. I have two major problems with this topic:

  1. We could argue that any/all best practices are foundational functionality and are “non-functional requirements”, as they are not directly driven by specific business requirements.

In fact, many of them are simply the result of the platform and context in which we are implementing these functional requirements. They are often more about the “how it is done” rather than the “what is done”. Moreover, best practices are typically non-functional requirements, yet we know (see bullets in #2 below) that best practices have an enormous benefit to software projects: increasing ROI (return on investment) and lowering TCO (total cost of ownership). As a result of this line of reasoning, we can also make the point that there is no such thing as “non-functional requirements” because they are simply the correct way to implement business requirements effectively.

  1. CRM business leadership often wants to defer the implementation of non-functional requirements (and perhaps we are mostly to blame if we do not explain that they are best practice initiatives).

Moreover, until recently, we didn’t have much data to support the value of best practices in a tangible way (e.g. increasing ROI or decreasing TCO). In order to help with this, I believe I have uncovered some useful information via some thoughtful prompting of Perplexity (numerous citations available if needed). Here are the data extracted from various reliable sources and studies:

  • Reduced Development Costs: 20-30% reduction
  • Increased Productivity: 20-40% boost
  • Improved Quality: 50-60% reduction in defects
  • Faster Time-to-Market: 15-25% acceleration
  • Enhanced Security: Reduced vulnerability to cyber threats
  • Better Resource Utilization: 15-25% improvement
  • Scalability and Flexibility: 30-50% improvement
  • Risk Reduction: 30-40% reduction in project risks

In addition, according to CRM.org, there is an $8.71 ROI on each dollar spent on CRM. This means, conservatively, CRM best practices have an approximate 85% ROI. Finally, it’s my opinion that anyone who has spent years in the CRM software world will agree these numbers are not particularly surprising.

2. When to Use Flows vs. Apex

The second topic is sometimes a controversial one: when to use Flows versus Apex. The essence of my opinion on this is that Flows are visual coding, and if they are not fairly simple (e.g. 20 or so elements/nodes or less), then they may be better off implemented in code. I have worked on Flows that quickly become monsters. In addition, the ability of a consultant (who is new to the project) to take over and understand and enhance a complex Flow can be more daunting than an Apex developer in the same situation looking at someone else’s code.

In my opinion, complex code is easier to uptake than a highly complex Flow. You also tend to pay a lower performance cost when implementing something fairly complex in Apex. The picture below helps provide some additional guidance:

Two final points to make here:

  1. We generally want to avoid mixing too many different types of automations for the same object (order of execution complexity).
  2. As the number of records increases (to six and seven orders of magnitude – e.g. 1M upwards), we tend to lean on Apex more to ensure our automations perform well within large-data-volume contexts.

3. Flow Best Practices Summary

The third topic is Flow best practices. Although there are several sources of this information available, I want to highlight some key ones:

  1. Flows should be fairly simple (e.g. less than 20 elements/nodes); otherwise, break the Flow up using Subflows.
  2. Avoid loops on objects with large numbers of records (unless using indexed fields effectively and knowing the result will be a manageable set of records).
  3. Be aware of how transactions work (and order of execution for Flows specifically): Flow transactions
  4. Be aware of the potential for ‘behind-the-scenes’ bulkification, as I call it, that occurs within Flows: Flow bulkification.
  5. Be aware of Flow recursion scenarios. There are complex scenarios when a Flow will recurse and other situations where it will not recurse. Please refer to this excellent writeup on the Salesforce Well-Architected website: Flow recursion. Regardless, this is another reason you need a quality Trigger Framework to help solve recursion more generally. 
  6. Screen Flows that are inherently asynchronous should consider leveraging Pause/Resume element(s) to complete intermediate transactions.
  7. Flows with nested loops must be avoided unless guaranteed to have a very low record count.
  8. Flows performing deletes should always add a Decision element before delete.
  9. If you have multiple Record-Triggered Flows with the same trigger type and start criteria, use the Trigger Order parameter.
  10. For business logic that is reused, create an Autolaunched Flow (or Screen Flow if UI).
  11. Use Fault Connectors in your Flow to handle errors and potentially display an error to the user.
  12. Use an Error Framework to log errors from Flows (just as you would for Apex and LWCs).

Another factor is performance. The following picture shows the relative performance of the various types of automations. However, we should point out that there are many caveats to creating a Flow that is “Before Save”, and so typically Flows are an order of magnitude slower than equivalent Apex code. Yet, due to their no-code/low-code approach, it is nice to use Flows if the requirements are fairly straightforward and performance is adequate.

4. Apex Best Practices Summary

The next logical topic is Apex best practices. In the interest of brevity, let me review and summarize the major Apex best practices.

  1. Security:
    • Use Sharing designation on class (with, without, inherited). Note: affects record visibility only.
    • User mode: WITH USER_MODE in SOQL is preferred over WITH_SECURITY_ENFORCED.
    • When possible, use DML that respects the current user’s privileges: Database.insert(new Account(name='foo'), AccessLevel.User_mode).
  2. Bulkifying code and avoiding DML or SOQL in Loops:
    • Pre-process list of records every time (e.g. Trigger.New).
    • As needed (often): Perform multiple SOQLs for the various objects involved and Use Maps to correlate them with each other.
  3. Common patterns for large sets of records and/or CPU-intensive code:
    • Batch-Apex, Queued-Apex (daisy-chaining if needed where the class invokes itself again as needed), or combination(s) of batching and queuing. Note that @future methods are the least preferable asynchronous Apex due to their caveats and limits.
    • Can use a progress-tracking custom object for noting where you have processing/DML failures, and perhaps which records you need to re-process.
  4. Leverage custom labels, field sets and/or custom metadata to provide configurability:
    • Need to document these for your team as part of the deliverables.
  5. Don’t eat Exceptions (typically need to re-throw them)!
  6. Use a Trigger Framework (recursion control, disabling, order-of-execution, diagnostics). Consider the easy-to-use but feature-rich Blackbelt Toolkit.
  7. Use an Error Framework/Management product to centralize, report and react automatically to errors for Apex, Flows, and Lightning Components. Again, consider the easy-to-use but feature-rich Blackbelt Toolkit.

5. Error Management Best Practices

Finally, this brings us to error management. This is an area where it is helpful to use a packaged solution to provide comprehensive error management for your Salesforce org. The goal here is to aggregate any Salesforce error (code, Flows, Lightning components, Event Monitoring alerts, etc.) into a single ErrorLog type object.

Moreover, what you really need is to automatically notify administrators when important errors occur. This should ideally be configurable based on the type of error that occurred – where you control the behavior via custom metadata. Examples of what you can do with a proper error management product are the following:

  1. Configure various categories of errors.
  2. Each category can then be configured to automatically do things such as: 1) write to an ErrorLog object, 2) send an email to an administrator, 3) re-throw an exception, 4) rollback the transaction, 5) write to the Debug Log, etc.
  3. Monitor failing Test Classes (in PROD or refreshed sandboxes) and log these errors via your Error Management solution as well.
  4. View the errors daily (via list-views) to easily view ErrorLog records and see the details regarding any particular error. Ideally, you also want a dashboard to summarize error activity over time and by category, exception type, or Apex class.

How Blackbelt Toolkit Can Help

The Blackbelt Toolkit is a single-managed package provided by Platform Technologies™. This Toolkit offers a bundle of five (and growing) products. Its purpose is to greatly simplify implementing best practices via the following tools/products:

  1. Trigger Framework provides configurable control over your Apex code such as: 1) fine-grained per-action/method recursion control, 2) disablement by user or time-based (e.g. for ETL loads), 3) performance diagnostics, and 4) optional helper methods.
  2. Error Management product aggregates various Salesforce errors (Apex code, Flows, Lightning Components, Apex-Exception-Emails, Batch Exceptions, Event Monitor alerts) into a single ErrorLog object and then allows you to categorize errors and configure automated actions such as: 1) notifying an administrator via email, 2) throwing an exception, 3) rolling back a transaction, 4) posting a Platform Event so your enterprise integration or enterprise log can be made aware of the error, and 5) logging to the debug log. We then also provide an Error Management Dashboard.
  3. Easy-to-use Rules Engine configured with simple custom metadata records. The Rules Engine supports multiple/varying scenarios, rule groups (rules are combined with AND or OR operators), and multiple disparate objects/records being passed in and having these declarative (and comparative) business rules applied, and then taking actions (such as Add, Subtract, Multiply, Assign) and returning a final result. We support most key data types such as Boolean, Numeric, Text, and Date, and the typical comparison operators.
  4. Test Class Manager to auto-detect failing test classes (via a scheduled batch class). This can be run in Sandboxes or Production on a regular basis. Error details are provided and fed into the Error Management product so automated actions can be taken (e.g. email an administrator).
  5. Finally, our Management Hierarchy product fills a gap in the Salesforce platform by providing a hierarchical management hierarchy (with support for multiple hierarchies/scenarios), and the most typical use-case for this is greatly simplifying Salesforce approval processes that require multiple managers/users in a hierarchy or list. This allows you to change the hierarchy without having to change your approval processes, and the hierarchy product could be used for custom business logic as well.

Platform Technologies is now offering a free POC for interested/qualified prospects. Please reach out to us via email (sales@platformtechnology.ai), on the AppExchange, or through our website.

Summary

In closing, I wanted to highlight the key technical best practices we should abide by in order to minimize technical debt and get the most value out of our CRM. I hope I provided some insights and updates to these, as well as some financial justification for focusing on best practices.

The Author

Patrick Fendt

Patrick is the CEO and Founder of Platform Technologies.

Leave a Reply