Mastering Control Structures in Apex : Loops and Iterators

Control structures are vital in Apex programming, as they help you manage the flow of your code based on conditions and iterations. This module focuses on three critical aspects of control structures in Apex: Conditional StatementsLoops, and Using Iterators for Collections.

Let’s dive deeper into each topic with examples tailored to the Apex environment.


1. Conditional Statements

Conditional statements in Apex allow you to execute blocks of code based on certain conditions. The primary types of conditional statements in Apex are:

if-else Statement

The if-else statement executes a block of code if a condition evaluates to true. If it evaluates to false, it can optionally execute another block of code.

Syntax:

if (condition) {
// Code to execute if condition is true
} else {
// Code to execute if condition is false
}

In case of if-else being looped, the else portion can be optional. If statements can also be grouped with the closest if as shown below.

if(i<=0) if(i==0) signal=0; else signal=-1;

The above can be interpreted as

if(i<=0){
if(i==0){
signal=0;
}else{
signal=-1;
}
}

Example:

public class ConditionalExample {
public static void checkDiscount(Integer purchaseAmount) {
if (purchaseAmount > 1000) {
System.debug('You get a 10% discount!');
} else {
System.debug('No discount available.');
}
}
}

Use Case: In Salesforce, you might use this to check if a lead’s score qualifies them for a special campaign.

switch Statement

A more cleaner and more efficient alternative to multiple if-else conditions is Switch statements in Apex.

Syntax:

switch on variable {
when value1 {
// Code for case value1
}
when value2 {
// Code for case value2
}
when else {
// Default case
}
}

Example:

public class SwitchExample {
public static void categorizeLead(String leadSource) {
switch on leadSource {
when 'Web' {
System.debug('Lead came from the website.');
}
when 'Phone' {
System.debug('Lead came through a phone call.');
}
when else {
System.debug('Unknown lead source.');
}
}
}
}

Use Case: You can use switch statements in Apex to handle record categorization or automate workflows based on a criteria.


2. Loops

Loops allow us to execute a block of code multiple times. In Apex, the most commonly used loops are forwhile, and do-while.

for

The for loop is ideal for iterating a fixed number of times or through a list.

Syntax:

for (initialization; condition; increment) {
// Code to execute
}

Example 1: Basic Iteration

public class ForLoopDemo {
public static void printNumbers() {
for (Integer i = 1; i <= 5; i++) {
System.debug('Number: ' + i);
}
}
}

Output
Number:1
Number:2
Number:3
Number:4
Number:5

Example 2: Looping Through a List

public class ListIterationDemo {
public static void displayContacts(List<Contact> contacts) {
for (Contact c : contacts) {
System.debug('Contact Name: ' + c.Name);
}
}
}

Use Case: Iterate through a list of Salesforce records to perform actions such as updating data or perform other operations on it.

while

The while loop executes as long as the specified condition evaluates to true.

Syntax:

while (condition) {
// Code to execute
}

Example:

public class WhileLoopDemo {
public static void countDown(Integer start) {

integer start = 100;
while (start > 0) {
System.debug('Countdown: ' + start);
start--;
}
}
}

Use Case: We use a while loop in Apex to monitor and process records until a condition is met, such as processing data with some limits.

do-while

The do-while loop ensures that the code block runs at least once before checking the condition.

Syntax:

do {
// Code to execute
} while (condition);

Example:

public class DoWhileDemo {
public static void guessNumber(Integer target) {
Integer guess = 0;
do {
guess++;
System.debug('Guessing: ' + guess);
} while (guess < target);
System.debug('Found the number: ' + target);
}
}

Use Case: This can be useful for scenarios like retrying API calls or attempting a database update until a condition is satisfied or the output is a success.


3. Using Iterators for Collections

Iterators are used to process elements in collections like lists, sets, and maps in a sequential manner. While loops and for-each loops work well for iterating over collections, iterators offer us more control.

1. Using Loops for Iteration

Apex provides different loops for iterating through collections:

List Iteration Example:

List<String> names = new List<String>{'Ajay', 'Barney', 'Carl'};
for (String name : names) {
System.debug(name);
}

Set Iteration Example:

Set<Integer> uniqueNumbers = new Set<Integer>{1, 2, 3};
for (Integer num : uniqueNumbers) {
System.debug(num);
}

Map Iteration Example:

Map<Integer, String> employeeMap = new Map<Integer, String>
{1 => 'Mary', 2 => 'Jane'};
for (Integer key : employeeMap.keySet()) {
System.debug('Key: ' + key + ', Value: ' + employeeMap.get(key));
}

Use Case: We can use for-each loops for simplicity when working with straightforward collections.

2. Using the Iterator Class

Salesforce also provides the Iterator interface, allowing you to process collections more flexibly. You can call methods like hasNext() and next() to manually traverse elements.

Example:

List<String> fruits = new List<String>{'Apple', 'Banana', 'Cherry'};
Iterator<String> fruitIterator = fruits.iterator();

while (fruitIterator.hasNext()) {
String fruit = fruitIterator.next();
System.debug(fruit);
}


Output:
Apple
Banana
Cherry

Use Case: We use Iterators when we need fine-grained control over the iteration process or when working with dynamically changing collections.

Key Methods in Iterator Interface

  • hasNext(): Checks if the next element is available.
  • next(): Retrieves the next element in the collection.

Best Practices on Loops in Salesforce

  1. Use Limits Class: Be mindful of governor limits in Salesforce, especially within loops.
    • Example: Use Limits.getQueries() to monitor SOQL queries inside loops.
  2. Bulkify Code: Process records in bulk to avoid hitting limits.
    • Example: Avoid DML operations within loops.
  3. Readable Conditions: Keep conditions easy to understand.
    • Example: Use descriptive variable names for better readability.

Let me know if you want an example tailored to a specific use case, like working with SOQL query results! 🚀

Until Next Lesson ! Keep Practicing ! Happy Coding!

Leave a Reply

error: Content is protected !!