Salesforce Performance Series: The forgotten art of APEX trigger frameworks

Regardless of the size of your Salesforce instance, chances are that you have deployed a trigger or two. Typically, larger organizations face performance issues and/or struggle to update their triggers due to the technical debt accumulated during the years. If you are in charge of a new organization you might be wondering where to get started in your quest to build a code structure ready to scale and easy to maintain.

This article will walk you through APEX trigger frameworks and how they can make you and your team successful. Trigger frameworks can seem daunting at first but they are really powerful to get the most out of your Salesforce org.

Not your typical performance tips ahead

If you have been around Salesforce for a few months, you have probably heard about the regular best practices to code in Salesforce:

  • Use before triggers to update the record that fired your trigger
  • Bulkify your database operations
  • Don’t do SOQL queries in for loops
  • Separate our business logic from the trigger class, etc…

This article will not try to cover the basics of coding in Salesforce but rather will walk you through setting up a performant code structure to write your trigger code and business code to accomplish 3 main goals:

  1. Code reusability and standardization by creating a Trigger Handler base class
  2. Maximum performance by reducing and optimizing the amount of database operations in a trigger
  3. Segregation of duties by keeping a clear difference between your boilerplate trigger code and the business logic.

Basic trigger structure

A regular implementation of a trigger will consist of two or more parts as shown below:

Image 1: Basic structure of an update trigger with a basic handler

At a first glance the image above seems to be pretty efficient as it separates business logic in a handler and follows other best practices. Additionally, since it only have two methods its pretty easy to read and debug.

Now, what happens if all methods fire and the business conditions are met? This code could potentially perform several update operations to the same records.

As we add methods and classes, it becomes cumbersome and time consuming to read the code and figure out which handlers are actually performing updates based on their conditions.

We can do better!

OK, talk to me about trigger frameworks

First, I want to clarify that I don’t take any credit for inventing trigger frameworks for APEX, a few authors have spent a lot of time perfecting theirs and I will link them below:

The goal of my article is to show you their advantages and empower you to use them when appropriate.

Let’s take a look at the basic components and structure

Image 2: Basic trigger framework components

So what do we gain from adding a dispatcher and an interface? Let me show you.

Reusability = time saved

The first and most basic characteristic of a trigger framework is that it defines an interface that will standardize your trigger handlers. The actual methods in the interface will vary depending on the implementation you choose (see the list above) but it will normally consist of the following:

  1. bulkBefore|bulkAfter methods: meant to collect list, sets or maps of data usually by querying the database. This is the perfect place to perform a SOQL query and save the results to use them later.
  2. before/after (insert, update, delete, undelete) methods: meant to perform non-bulkified operations on single records in the trigger context. Do not perform SOQL operations here as they will run once per record.
  3. andFinally method: meant to run once at the end of the trigger. This is the best place to update related records or commit to the database in general.

The structure above will give you and your developer team a clear cookbook to build a trigger and most importantly it allows you to scale up very easily and efficiently.

Performance is king

As your organization grows, so will your code and business requirement complexity. Slowing down the time that it takes to save an opportunity or update a simple record has to be avoided at all costs. Trigger frameworks will add a few tools to your ninja tool belt to improve performance and reduce errors as your code base grows:

  1. Using the bulk and finally methods will make sure you developers optimize their DML operations. The “bulk” methods will provide a familiar place to look for already existing SOQL queries that could be useful when coding new requirements. The “finally” methods will force your developers to consolidate their database commits and will reduce the chance of updating the same record twice because a developer didn’t check other code for similar DML commits.
  2. Trigger frameworks provide a built in way to deal with recursive operations. As you have probably found out, “after update” methods like to run multiple times when another transaction updates the record like a process builder or workflow. Most trigger frameworks will provide a recursion counter that you can use instead of having to create static variables every time.
  3. Disabling triggers on demand allows your operations to be efficient. It is very common to have to disable triggers when doing a big load or when integrating different code sections. Most frameworks have both metadata types to disable trigger temporarily or APEX APIs to disable them on an APEX transaction. These functions will become useful as your requirement complexity increases.

Code readability and segregation of duties

As we saw in the original example, the regular trigger handler structure provides an easy to read structure when you have a small code base. As your code grows it can become a pain to go method by method in the handler to see which one does SOQL queries and which one updates records.

Trigger frameworks will help you keep your trigger clean, the trigger handler readable and will enable your developers to create Helper classes if needed to separate business logic. At the end of the day, if you need to update code you will have a very clear reading flow in your handler class to any method you want to update depending on your business logic.

What is next?

In this article I have shown you the basics of trigger frameworks and how they can help you and your team work more efficiently. From maximum performance, reusability and readability you will do your future self a favor by following basic framework standards.

I hope this article has inspired you to take a closer look into the existing trigger frameworks and even customize your own. If you are just starting your code base, use the links below to find the quick starters on several frameworks:

If you are developer jumping into an existing code base, plan well your move to a framework and start from small chunks of code and business logic to maximize impact. Happy coding

About me

Article by Stefan Zepeda
Hands-on Technical Architect and Salesforce enthusiast with experience collecting requirements, transforming them into solutions and implementing them efficiently on the Salesforce platform.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s