In Salesforce, Batch Apex is essential for processing large data volumes that exceed the governor limits for regular Apex operations. The Database.Batchable interface provides the necessary framework for breaking down large data sets into manageable chunks.
The three primary methods in the Database.Batchable interfaces are:
- Start: Initiates the batch process. This method returns a QueryLocator or Iterable which defines the dataset to be processed.
- Execute: This method processes each chunk of records. It’s where the logic for handling the data in batches is defined.
- Finish: Executes any post-processing tasks once all chunks have been processed, such as sending a notification or logging results.
While these methods are foundational, custom methods in your Batch Apex class can significantly enhance functionality. Let’s explore how to elevate your batch classes with these custom methods, addressing key concerns such as error handling, scalability, and overall code readability.
Why do we need Custom Methods in Batch Apex
Custom methods within a Batch Apex class provide several benefits, including:
- Separation of Concerns: By creating dedicated methods for specific tasks (e.g., data transformation, validation, etc.), you can keep your class modular and more readable.
- Reusability: Custom methods allow you to write logic once and reuse it across different parts of the batch process. This helps in reducing redundancy.
- Maintainability: By breaking down logic into smaller, well-defined methods, you make your code easier to maintain in the long run. This also allows for easier unit testing of isolated methods.
Real-World Scenario: Customer Data Cleanup
Business Requirements
- Standardize Phone Numbers: Format all Contact.Phone values to (XXX) XXX-XXXX.
- Validate Emails: Flag invalid emails and clear them from records.
- Generate a Summary Report: Email admins with success/failure metrics.
Technical Challenges
- Processing millions of records without hitting governor limits.
- Retaining error details across batches.
- Ensuring email validation aligns with organizational standards.
Batch Class Code:
Explanation:
Let’s break down the Batch Apex code and its custom methods with real-world examples to illustrate how it works. We’ll use the ContactCleanupBatch class as a reference.
The ContactCleanupBatch class implements Database.Batchable and Database.Stateful to process Contact records in batches.
Key Components:
- Stateful Variables: Track progress across batches (totalProcessed, errors, errorMessages).
- Core Methods: start, execute, finish.
- Custom Methods: formatPhoneNumber, validateEmail, sendSummaryEmail.
Start Method:
Define the scope of records to process.
Explanation:
- Queries all Contact records with non-null Phone or Email fields.
- Example: If there are 10,000 Contacts with phone numbers or emails, this query fetches them for processing.
Execute Method:
Process each batch of records (default batch size: 200).
Step-by-Step Explanation:
1. Input: A batch of up to 200 Contact records.
2. Process Each Contact:
Format Phone: Use formatPhoneNumber to standardize the format.
Example: “123-456-7890” ➔ “(123) 456-7890”.
Validate Email: Use validateEmail with regex to check validity.
Valid: “user@example.com” ➔ allowed.
Invalid: “user@invalid” ➔ email cleared, error logged.
3.Bulk DML Update: Updates all processed contacts in one operation to avoid hitting DML limits.
Custom Method formatPhoneNumber:
Standardize phone numbers to (XXX) XXX-XXXX.
Examples:
- Input: “123.456.7890” ➔ cleaned to “1234567890” ➔ output “(123) 456-7890”.
- Input:
"1234"
➔ length ≠ 10 ➔ returns original value.
Custom Method validateEmail
Validate emails using regex.
Examples:
Valid: “john.doe@example.com” ➔ returns true.
Invalid: “jane@.com” ➔ returns false.
Finish Method & sendSummaryEmail
Send a summary email after all batches complete.
Example Email Output:
Total Contacts Processed: 5000
Errors: 12
Error Details:
Invalid email for Contact ID 003xx000001TUVW: user@invalid
Error processing Contact ID 003xx000002WXYZ: Script-thrown exception
Testing the Batch
Test Class Example:
Preparing for Salesforce Certification Exams? Check out the practice sets here
Real-World Scenario Walkthrough
Scenario: Clean up 50,000 Contact records.
1. Batch Execution:
- start(): Fetches all 50,000 records.
- execute(): Processes 200 records at a time (250 batches).
- Each batch formats phones validates emails, and logs errors.
2. Result:
- 48,000 contacts updated successfully.
- 2000 errors logged (e.g., invalid emails).
- Summary email sent to the admin.
Also Read – Batch Apex Scenario-Based Interview Questions and Answers
FAQs:
1. What is a custom method in an Apex Batch class and why would I need one?
A custom method in an Apex Batch class is a user-defined method that performs specific operations outside the standard start, execute, and finish methods. You might need a custom method to:
- Reuse code logic across multiple methods.
- Perform pre-processing or post-processing tasks.
- Encapsulate complex logic for better readability and maintainability.
2. Is it possible to test custom methods in a Batch class?
Yes, you can test custom methods by writing unit tests for your Batch class. Use the Test.startTest() and Test.stopTest() methods to execute the batch and verify the behaviour of your custom methods.
3. Can I use a custom method to send emails or notifications during batch execution?
Yes, you can use a custom method to send emails or notifications. However, be mindful of the email sending limits (e.g., Messaging.sendEmail limits) and ensure the logic is bulkified.
4. What happens if a custom method throws an exception in a Batch class?
If a custom method throws an exception, it will interrupt the batch execution for the current chunk. Use try-catch blocks to handle exceptions gracefully and log errors for debugging.
Conclusion
By combining Batch Apex with custom methods, you can efficiently process large datasets while maintaining code readability and security. Let me know if you’d like to explore more complex scenarios.