Saturday 15 August 2020

Episode -8 Frequently Asked Interview Questions on Batch Apex in Salesforce

 


In this blog, we will have insights about the interview questions you must prepare for the batch apex topic in salesforce.

Before reading this blog I will recommend you, read my previous blog on the batch apex to understand the concepts better. Below is the link for it:


Without wasting time, let's get started.😉


1. What is the use of the Database. Stateful interface in Batch Apex?


As you know the execution of the batch apex job is considered to be a discrete transaction. For Example, if you have 1000 records to process and you have mentioned the batch size of 100 records then you will have 10 discrete transactions. So, In this way, the batch apex is stateless by default. By stateless, it means for each execution of the execute method, you will have a fresh copy of the object.
Now if there is the requirement, you have to count the total no of records that are processed by your batch apex class then you cannot simply define the logic to count the records in the execute method because the variable will reset its value for every batch transaction (let's say after processing 100 records in our case). So to maintain state across these transactions, we need to implement Database.Stateful interface.

Note: In Case of Database.Stateful Interface , only instance member variables retain their value between transactions whereas static variables reset their values and thus do not retain their values between transactions.

Let's understand it using an example via code:

Requirement: You want to count the total no of Hot Leads( leads having Rating as Hot) processed by the apex class and update the description field as well.


global class HotLeads implements Database.Batchable<sObject>,Database.Stateful{
    
    global integer NumberOfHotLeads=0;
    // Start method: collects all the lead records meeting the specified criteria
    
    global Database.QueryLocator start(Database.BatchableContext bc){
        String query='select Id,Rating from Lead where Rating=\'Hot\'';
        return Database.getQueryLocator(query);     
    }
    
    //Execute method: Taking a list of lead records returned  by start method  as a parameter
    // and Updating the lead description
    
    global  void execute(Database.BatchableContext bc,List<Lead> leadRecords){
        for(Lead l: leadRecords){
            l.Description='This is the Qualified lead who is highly interested in the product'; 
            NumberOfHotLeads++;
        }
        update leadRecords;
        
    }
    
    //Finish Method 
    
    global void finish(Database.BatchableContext bc){
        
        System.debug('No of  records processed Successfully are :' +NumberOfHotLeads);
        AsyncApexJob job= [select id,Status,JobItemsProcessed,TotalJobItems,NumberofErrors
                           from AsyncApexJob where id = :bc.getJobId()];
        
        // sends a notification email to the job submitter that includes the job info and number of leads updated.    
    }
}


2. Can we call one Batch Class from Another Batch Class? If yes then How?

Yes, we can call one batch class from another batch class only in the finish method of the batch apex.
Once the execution of records gets completed, then the finish method calls another apex batch class.
You can chain maximum of 5 Batch jobs to one another.
 
For Example, if you want to call the above class HotLeads from the apex class, then see the code below:

global class LeadsChainingExample implements Database.Batchable<sObject>{
    
    // Start method: collects all the lead records 
    
    global Database.QueryLocator start(Database.BatchableContext bc){
        String query='select Id,Rating from Lead limit 10000';
        return Database.getQueryLocator(query);     
    }
    
    //Execute method: Taking a list of lead records returned  by start method  as a parameter
    
       global  void execute(Database.BatchableContext bc,List<Lead> leadRecords){
        for(Lead l: leadRecords){
            //add your logic    
        }
    }
    
    //Finish Method 
   
    global void finish(Database.BatchableContext bc){
    
//chaining of jobs
        Database.executeBatch(new HotLeads());    
    }
}

NOTE: If you try to call batch apex from start () or execute () method, the class will throw below runtime error.

System.AsyncException: Database.executeBatch cannot be called from a batch start, batch execute, or future method.


3. Can we call Future Methods in Batch Apex?

No, we cannot directly call the future methods from the batch apex. But there is a workaround to call the future method using web services. The apex class can call the webservice which can call the @future method further.


4. Can we Schedule the Batch Apex?

Yes, we can schedule the batch apex using below two methods.

a.)Using the Schedule Apex functionality

Steps:
  •  Go to Setup and search apex classes in the quick find box 
  • Click on the Schedule Apex Button as seen in the below screenshot.

  • Fill out the below information on the Schedule Apex Record Page


  • The Apex class here  should be the Scheduler class -apex class that implements Schedulable interface and have execute method in it that takes the parameter of type SchedulableContext as shown in the below code
global class BatchScheduleClassExample implements Schedulable {   
global void execute(SchedulableContext ctx) {
    HotLeads  batch = new HotLeads ();
    database.executebatch(batch);
      }
}

b). Using System.Schedule method in Schedulable Apex

System.schedule method has three parameters:
  • Name of the job
  • An expression that represents the time and date of the job  in below format:
Seconds Minutes Hours Day_of_month Month Day_of_week Optional_year
  • An instance of the batch apex class
Code Example:

global class BatchScheduleClassExample implements Schedulable {   
global void execute(SchedulableContext ctx) {
    HotLeads  batch = new HotLeads ();
    String cronStr = '20 30 8 10 2 ?';
    String jobID = System.schedule('Process Lead Records', cronStr, batch);  
     }
}


5. What is the difference between Database.queryLocator object or an Iterable <Sobject>

The start method of the batch apex class returns either the Database.queryLocator object or an iterable to contain the records that is passed to the execute method.

Database.queryLocator Object
  • when to use: It is generally used when you are using a simple SOQL select query to collect the records
  • Governor Limits: If you are using Database.queryLocator object then-governor limits for the total no of records retrieved by SOQL query is bypassed. It means by using it you can collect up to 50 million records of your org object.
Iterable <Sobject>
  • When to use: It is generally used when you want to create your own custom process for iterating the list of records.
  • Governor Limits: If you are using the Iterable object then-governor limits for the total no of records retrieved by the SOQL query are still enforced.

Some More Interview Questions:

  1. What is Batch Apex?
  2. Why do we use Batch Apex?
  3. What are the methods (with syntax)used in Batch Apex?
  4. How can we track the status of the currently running batch Job?
  5. What is the purpose of using start(),execute() and finish() method in batch apex?
  6. What is the maximum and the default size of the batch?
You will get all the answers of the above questions in my previous blog. Read the blog and find out the answers yourself with a detailed description. Click on the link below for it :


This is from my side. I hope you have learned a lot of concepts about batch apex. Do like and follow my blog to stay tuned. You can also comment on what more questions you have faced related to batch apex in your interviews. I can add them to my list. Until then keep learning and sharing your knowledge.✌















































4 comments:

  1. Great! Liked the descriptive solutions. You made it really easy to understand.
    Keep posting more content :)

    ReplyDelete
    Replies
    1. Thanks.Keep Reading and follow my blog for more content.Sure will post more valuable content.

      Delete
  2. Very informative. Thanks for Sharing

    ReplyDelete

If you have any doubts ,Please let me know.

Episode 13 : RollUp Summary Trigger for Lookup Relationship

 As we all know we can use roll-up summary field logic only for the master-detail relationship, but in case you have the business requiremen...