SalesforceBlue

Feel the rhythm of Salesforce

Apex

Apex Trigger Handler Simplified

Let’s start with a question “We can write all the logic into one single trigger then why should we create a separate Apex Trigger Handler?

Suppose you are a great chef and wanted to take your cooking journey to the next level.

In the early days, only you used to take the orders, cook the food and serve them back to customers.

As you get popular and the number of order increase it will be a challenging situation for you to maintain taking orders, cooking and serving back to customers efficiently.

To manage things efficiently you will be doing some separation of activities by hiring a waiter who took and serves the order back to customers while you can cook the food. This will let you have a proper structure of responsibilities and efficient management.

Similarly, as you keep on writing all the code into a single trigger it would be a maintenance challenge at some point in time along with a hard-to-read code structure.

Technically you can write all the logic into a single trigger but it is always best to focus on writing a robust, maintainable, and well-structured application.

There should be a separation of concerns within your application for better maintainability and a well-structured application.

Thus, the trigger should act as an entry point for DML operations and delegate the business logic to the specific handler classes.

Let’s see the below image to see the separation of concerns.

We have created a Trigger that will act as an entry point for a DML operation. The handler class will accept the trigger context variables as input and will perform the business logic.

Let’s re-write the duplicate check trigger which we covered in Apex Trigger with Trigger Handlers.

Trigger :

trigger ContactTrigger on Contact (before insert, before update, after undelete) {
    ContactTriggerHandler.doDuplicateCheck(Trigger.new, Trigger.old);
}

The trigger is invoking the handler class method with Trigger context variables passed as a parameter.

Handler :

public with sharing class ContactTriggerHandler {

    public static void doDuplicateCheck(List<Contact> newList, List<Contact> oldList) {
        Set<String> emailSetNew = new Set<String>();
        Set<String> emailSetExisting = new Set<String>();
    
        for(Contact con : newList) {
            // Assuming Email will be made a mandatory Field 
            emailSetNew.add(con.Email); 
        }
    
        for(Contact con : [SELECT Id, Email FROM Contact WHERE Email =: emailSetNew]) {
            emailSetExisting.add((con.Email).toUpperCase());
        }
        
        for(Contact con : newList) {
            if(emailSetExisting.contains((con.Email).toUpperCase())) {
                con.addError('Duplicate Email Found!');
            }
        }
    }
}

The handler has the logic where we are doing the duplicate check and throwing an error. It is accepting the trigger context variables as input and deriving whether there is a duplicate contact present.

As per the best practice, we should only have a “Single Trigger Per Object”.

What we did above by delegating the business logic from the trigger to the handler can be further refactored into a more optimal single line Trigger, dispatcher classes and respective handlers.

In general, we should always follow the best practices and follow the right design patterns as per the requirements.

Thank you for visiting SalesforceBlue.com
If you have any queries feel free to write down a comment below 🙂


One thought on “Apex Trigger Handler Simplified

  • 👍👌 This article 📝 beautifully explains why it’s important to create a separate Apex Trigger Handler instead of writing all the logic into one single trigger. Just like a great chef 👨‍🍳 who hires a waiter to serve customers 🍽️ while focusing on cooking 🍳, it’s essential to separate concerns within the application to ensure maintainability and a well-structured code 🏗️. Delegating business logic to specific handler classes not only makes the code more readable 👀 but also enables efficient management 💼. The author has provided a clear example to illustrate the separation of concerns in the application, making it easy for readers to understand 🤔. It’s always better to follow the best practices and design patterns to ensure a robust and maintainable application 🚀. Great work! 👏👏

    Reply

Leave a Reply

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