Header Ads Widget

Responsive Advertisement

Apex - Intermediate Topics

 Apex Test Classes

Importance of Testing in Apex

Testing is crucial in Apex to ensure code quality and reliability. Salesforce requires at least 75% test coverage for deployment to production.

Writing Test Methods

Test methods validate the functionality of your code.

@isTest
public class CalculatorTest {
    @isTest
    static void testAdd() {
        Calculator calc = new Calculator();
        Integer result = calc.add(2, 3);
        System.assertEquals(5, result);
    }
}


Using Test Data

Test data ensures your tests are isolated from actual data.

@isTest
static void testWithData() {
    Account acc = new Account(Name='Test Account');
    insert acc;
 
    // Test logic
}


Test Coverage and Best Practices

  • Aim for 75% test coverage.
  • Use Test.startTest() and Test.stopTest() for testing governor limits.
  • Test both positive and negative scenarios.

 

Apex Governor Limits

Understanding Governor Limits

Salesforce enforces limits to ensure efficient resource usage, such as limits on SOQL queries, DML statements, and CPU time.

Best Practices to Avoid Hitting Limits

  • Bulkify code: Process records in bulk rather than one at a time.
  • Use collections.
  • Use SOQL for loops.
  • Avoid unnecessary queries and DML statements within loops.

Tools for Monitoring Limits

  • Debug logs
  • Salesforce Developer Console
  • System Limits

 

Apex Best Practices

Code Readability and Maintainability

  • Use meaningful variable names.
  • Comment your code.
  • Follow consistent coding standards.

Avoiding Common Pitfalls

  • Avoid hardcoding IDs.
  • Handle exceptions properly.
  • Ensure trigger logic is bulk-safe.

Using Design Patterns in Apex

  • Singleton: Ensure a class has only one instance.
  • Factory: Create objects without specifying the exact class.

 

Apex Batch Processing

Introduction to Batch Apex

Used for processing large volumes of data asynchronously.

Writing and Scheduling Batch Classes

public class BatchExample implements Database.Batchable<sObject> {
    public Database.QueryLocator start(Database.BatchableContext BC) {
        return Database.getQueryLocator([SELECT Id, Name FROM Account]);
    }
    public void execute(Database.BatchableContext BC, List<Account> scope) {
        for (Account acc : scope) {
            acc.Description = 'Batch Processed';
        }
        update scope;
    }
    public void finish(Database.BatchableContext BC) {
        System.debug('Batch processing completed');
    }
}
 
// Scheduling
BatchExample batch = new BatchExample();
Database.executeBatch(batch);


Use Cases for Batch Processing

  • Data cleanup
  • Mass updates
  • Integration with external systems

 

Asynchronous Apex

Future Methods

Future methods run asynchronously and are used for operations that require callouts to external services or that need to be performed in the background.

@future
public static void futureMethod() {
    // Asynchronous logic
}


Queueable Apex

Queueable Apex allows for more complex job chaining compared to future methods.

public class QueueableExample implements Queueable {
    public void execute(QueueableContext context) {
        // Queueable logic
    }
}
 
// Enqueue
System.enqueueJob(new QueueableExample());


Scheduled Apex

Scheduled Apex allows you to schedule Apex code to run at specific times.

public class ScheduledExample implements Schedulable {
    public void execute(SchedulableContext SC) {
        // Scheduled logic
    }
}
 
// Scheduling
ScheduledExample schedule = new ScheduledExample();
String cronExp = '0 0 12 * * ?';
System.schedule('Daily Job', cronExp, schedule);


Assignment:

·         Write a test class for the Car class you created earlier, testing the constructor and the method to display car details.

·         Write a bulkified trigger on the Contact object that updates the Description field for multiple contacts in a single DML operation.

·         Refactor your Car class to follow best practices for readability and maintainability. Add comments and meaningful variable names.

·         Write a batch class that updates the Description field of all accounts in your org. Schedule this batch to run immediately.

·         Write a future method to make a callout to an external service and print the response. Also, write a scheduled job that runs this future method every day at noon.


For more in-depth tutorials and learning paths, refer to the following resources:

Happy learning!

Post a Comment

0 Comments