Mastering Control Structures and Loops in Salesforce Apex — Apex Part 4

Mohammad Usman
4 min readMar 15, 2024

--

Control structures and loops are fundamental components of any programming language, including Apex, the proprietary language for Salesforce development. In this article, we’ll delve into the usage of conditional statements and loops in Apex, exploring their syntax, best practices, and common scenarios where they are applied.

Conditional Statements

Conditional statements allow developers to execute different blocks of code based on certain conditions. In Apex, the primary conditional statements are `if-else` and `switch`.

1. `if-else` Statements:

The `if-else` statement in Apex allows you to execute a block of code if a specified condition is true and another block of code if the condition is false.

Integer x = 10;
if(x > 5) {
System.debug(‘x is greater than 5’);
} else {
System.debug(‘x is less than or equal to 5’);
}

2. `switch` Statements:

The `switch` statement evaluates a variable or expression against a list of possible values and executes the corresponding block of code based on a match.

String day = ‘Monday’;
switch on day {
when ‘Monday’ {
System.debug(‘It is Monday!’);
}
when ‘Tuesday’ {
System.debug(‘It is Tuesday!’);
}
when else {
System.debug(‘It is another day of the week.’);
}
}

Loops

Loops allow developers to iterate over a block of code multiple times until a specified condition is met. Apex supports `for`, `while`, and `do-while` loops.

1. `for` Loops:

The `for` loop in Apex allows you to iterate over a collection (such as a list or set) or execute a block of code a specified number of times.

List<Integer> numbers = new List<Integer>{1, 2, 3, 4, 5};
for(Integer i = 0; i < numbers.size(); i++) {
System.debug(‘Number: ‘ + numbers[i]);
}

2. `while` Loops:

The `while` loop executes a block of code as long as a specified condition evaluates to true.

Integer count = 0;
while(count < 5) {
System.debug(‘Count: ‘ + count);
count++;
}

3. `do-while` Loops:

Similar to the `while` loop, the `do-while` loop executes a block of code while a specified condition is true. However, it always executes the block of code at least once before checking the condition.

Integer num = 1;
do {
System.debug(‘Number: ‘ + num);
num++;
} while(num <= 5);

Using Loops and Conditionals in Apex

Now that we’ve covered the basics of control structures and loops in Apex, let’s explore some common scenarios where they are applied:

1. Data Processing:

Loops are commonly used for iterating over records retrieved from the Salesforce database or external systems. For example, you might use a `for` loop to process a list of Opportunity records and perform certain calculations.

List<Opportunity> opportunities = [SELECT Id, Amount FROM Opportunity];
for(Opportunity opp : opportunities) {
if(opp.Amount > 10000) {
// Perform additional processing
}
}

2. Workflow Automation:

Conditional statements are essential for implementing complex workflow logic. For instance, you might use an `if-else` statement to determine the appropriate action based on the stage of a Lead or Opportunity.

if(lead.Status == ‘New’) {
// Perform lead qualification
} else if(lead.Status == ‘Contacted’) {
// Schedule follow-up
} else {
// Close the lead
}

3. Error Handling:

Conditional statements are often used for error handling and exception management. You can use `if-else` statements to check for specific error conditions and handle them appropriately.

try {
// Perform operation that might throw an exception
} catch(Exception ex) {
if(ex.getMessage().contains(‘custom_error’)) {
// Handle custom error
} else {
// Handle other exceptions
}
}

Resources for Further Learning

To further enhance your understanding of advanced Apex features and Salesforce development in general, here are some recommended resources:

- Salesforce Apex Developer Guide: The official Apex developer guide provides comprehensive documentation and examples for mastering Apex programming.
- Trailhead: Salesforce’s interactive learning platform offers a wide range of modules and trails on Apex development, asynchronous processing, integrations, and more.
- Salesforce Developer Blog: Stay updated with the latest news, tips, and best practices from Salesforce developers and experts through the official developer blog.
- Stack Exchange — Salesforce: Engage with the Salesforce community, ask questions, and share knowledge on Stack Exchange’s dedicated Salesforce platform.

Conclusion

Control structures and loops are indispensable tools in Apex programming, enabling developers to implement complex logic, iterate over data collections, and handle various scenarios effectively. By mastering these concepts and understanding their practical applications, you can write more efficient and robust Salesforce applications.

--

--

Mohammad Usman

Trailblazer | Transforming Businesses through Salesforce Expertise | Salesforce Technical Architect, Consultant & Developer | Technical Lead