Guide To Writing Batchable Classes In Salesforce : Salesforce

Guide To Writing Batchable Classes In Salesforce
by: Salesforce
blow post content copied from  Forcetalks
click here to view original post


Ever heard of “Batch classes” in Salesforce and felt a bit puzzled? Don’t worry; it’s simpler than you think! Imagine you’re baking cookies. You don’t bake one at a time; that would take forever, right? Instead, you bake them in batches—smaller groups that make your task easier. Well, Salesforce batch classes work just like that! They help developers manage lots of data in smaller, more manageable pieces. Let’s unravel the mystery of batch classes, just like baking cookies in your kitchen!

Now that you know what is a Batch class. Let’s understand how it works

What is a Batch Class?

A batch class is a type of Apex class that allows you to process large volumes of records asynchronously in batches. Salesforce provides a feature called Batch Apex that enables developers to create batch classes for tasks like data processing, cleaning, and transformation. Batch Apex is especially useful when dealing with large datasets, as it breaks down the data into manageable chunks, processes them in separate transactions, and helps avoid governor limits imposed by the Salesforce platform.

Why Do We Use Batch Classes?

Now that you know how to create a Batchable Class, let’s explore the benefits:

  1. Managing Big Tasks: Batch classes are like superheroes for developers dealing with heaps of data. When you have thousands of records to handle, batch classes divide them into smaller groups, making them easier to manage.
  2. Avoiding Overload: Imagine carrying a heavy load of groceries. If you try to carry everything at once, it becomes overwhelming. Batch classes prevent this overload in Salesforce by dividing tasks into smaller, more manageable portions.
  3. Keeping Things Organized: Batch classes help organize data tasks neatly. Just like filing papers into folders, batch classes process data efficiently, ensuring nothing gets misplaced or overlooked.

dont miss out iconDon't forget to check out: What is Batch Apex in Salesforce? A Definitive Guide

When not to use Batch Classes?

  1. Real-time Requirements: If your application requires real-time processing and immediate responses to user actions, batch processing might not be suitable. Batch processing is inherently
    designed for processing data in bulk and might introduce latency, making it unsuitable for real-time applications.
  2. Frequent Data Updates: If the data being processed is constantly changing or being updated at a high frequency, using batch processing can lead to data consistency issues. In such dynamic environments, real-time or near-real-time processing methods might be more appropriate to maintain data integrity

How to Implement Batch Class and its Methods?

A batch class must implement the Database.Batchable<SObject> interface, which includes three main methods: start, execute, and finish.

Three Pillars of Batch Classes

Start Method: Setting the Stage

The start method is like the moment you decide how to group the marbles. For example, you might decide to start with all the blue marbles. This method helps you figure out which marbles to work on first. It’s like picking the right marbles for your sorting game.

In technical terms, the start method is responsible for figuring out the first batch of data (the marbles in our example) that needs to be sorted. It helps the computer know where to begin the sorting process.

Execute Method: Work in Progress

Now, let’s say you have a special machine to sort the marbles. You put a small group of marbles into the machine, and it sorts them based on their colors.

The execute method is like the machine doing its job. It takes the group of marbles you’ve chosen and starts sorting them. In our case, it could be sorting the blue marbles from the rest. This method handles each small group of marbles one at a time, making sure they are sorted properly.

Finish Method: Completing the Task

Lastly, after all the marbles are sorted into different groups, you want to make sure everything is finished and nothing is left behind.

The finish method is like checking to see if all the marbles are sorted. If they are, you can say, “Great job, everything is done!” It’s the final step that tells you the task is complete and successful.

Now Let’s Implement this with a Practical Example

Send a personalized welcome email to new leads in Salesforce:

Global class WelcomeEmailBatch implements Database.Batchable<SObject>{
        global Database.QueryLocator start(Database.BatchableContext BC) {
        // Query new leads created in the last 7 days
        Date lastWeek = Date.today().addDays(-7);
        return Database.getQueryLocator(
            'SELECT Id, Name, Email FROM Lead WHERE CreatedDate >= :lastWeek AND IsConverted = false AND WelcomeEmailSent__c = false'
        );
    }
    global void execute(Database.BatchableContext BC, List<Lead> leadList) {
        List<Messaging.SingleEmailMessage> emails = new List<Messaging.SingleEmailMessage>();
        List <Lead> updatedLead = new List <Lead>();
        for(Lead lead : leadList) {
            // Compose personalized email message
            Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
            email.setToAddresses(new String[]{lead.Email});
            email.setSubject('Welcome to Our Company, ' + lead.Name + '!');
            email.setPlainTextBody('Dear ' + lead.Name + ',\n\nWelcome to Our Company! Thank you for expressing your interest. We are excited to have you on board.\n\nBest regards,\nYour Organization');
            emails.add(email);
            lead.WelcomeEmailSent__c = true;
            updatedLead.add(lead);
        }    
        // Send email messages
        Messaging.sendEmail(emails);
        if(!updatedLead.isEmpty()){
            update updatedLead;
        }
    }
    global void finish(Database.BatchableContext BC) {
        // Perform any post-processing tasks if needed
        System.debug('Welcome emails sent successfully!');
    }
}

Let’s break down its components to understand its functionality better.

Start Method: Setting the Stage

The start method initiates the batch process, fetching new leads created in the last 7 days that are yet to be converted. It constructs a query locator to pinpoint the desired leads based on specific criteria, ensuring a targeted approach.

Execute Method: Crafting Personalized Emails

Inside the execute method, the batch class processes leads in chunks. For each lead in the scope, it composes a personalized welcome email. The emails are customized with the lead’s name and contain a warm greeting, expressing gratitude for their interest and enthusiasm about their collaboration.

Finish Method: Wrapping Up with Feedback

After the emails have been sent, the finish method comes into play. It serves as a post-processing step, allowing for additional tasks. In this case, the method logs a debug statement indicating the successful dispatch of welcome emails.

Trailhead Modules for Further Learning

If you want to dive deeper into Batchable Classes and Salesforce development, Salesforce’s Trailhead offers a wealth of resources and interactive modules. Here are some Trailhead modules you can explore:

  1. Apex Basics & Database: This module covers the basics of Apex, including Batchable Classes, triggers, and database operations.
  2. Asynchronous Apex: Learn how to use Batchable Classes, Queueable Apex, and more for efficient data processing in Salesforce.
  3. Apex Testing: Discover best practices for testing your Batchable Classes and ensuring the reliability of your code.

dont miss out iconCheck out another amazing blog here: Salesforce Security Interview Questions

Conclusion

So, whether you’re baking cookies in your kitchen or sorting marbles with friends, remember the simplicity of breaking tasks into manageable pieces. In the same way, Salesforce batch classes empower you to conquer the most significant challenges, one batch at a time.

The post Guide To Writing Batchable Classes In Salesforce appeared first on Forcetalks.


November 23, 2023 at 04:54PM
Click here for more details...

=============================
The original post is available in Forcetalks by Salesforce
this post has been published as it is through automation. Automation script brings all the top bloggers post under a single umbrella.
The purpose of this blog, Follow the top Salesforce bloggers and collect all blogs in a single place through automation.
============================

Salesforce