Loops in Salesforce Apex
Loops are essential constructs in programming that allow you to repeat a block of code multiple times based on a condition. Salesforce Apex supports three types of loops: FOR
, WHILE
, and DO-WHILE
. Each of these loops serves different purposes and can be used in various scenarios depending on the requirements.
1. FOR Loop
The FOR
loop in Apex is used when you know in advance how many times you want to execute a statement or a block of statements. It is the most commonly used loop in Apex.
Syntax:
for (initialization; condition; increment) {
// Code to be executed
}
- Initialization: This step is executed only once before the loop starts. It usually involves declaring and initializing a counter variable.
- Condition: Before each iteration, the condition is evaluated. If it evaluates to
true
, the loop continues; iffalse
, the loop terminates. - Increment: This step is executed after each iteration and typically increments or decrements the counter.
Example:
Imagine you are working with a list of custom objects Invoice__c
and you want to apply a 10% discount to each invoice in the list.
// List of invoices
List<Invoice__c> invoices = [SELECT Id, Amount__c FROM Invoice__c];
// Loop through each invoice
for (Integer i = 0; i < invoices.size(); i++) {
// Apply 10% discount
invoices[i].Amount__c = invoices[i].Amount__c * 0.9;
}
// Update the invoices in the database
update invoices;
In this example, the FOR
loop iterates through the list of invoices, applying a discount to each one. The loop starts with i = 0
, checks if i
is less than the size of the invoices
list, and increments i
by 1 after each iteration.
2. WHILE Loop
The WHILE
loop is used when the number of iterations is not known beforehand, and you need to continue looping until a certain condition is met.
Syntax:
while (condition) {
// Code to be executed
}
- Condition: The loop continues to execute as long as the condition is
true
. If the condition isfalse
initially, the code inside the loop will not execute at all.
Example:
Suppose you have a process where you need to keep checking for a specific condition, such as waiting for a record to be processed by an external system before proceeding.
// Simulated processing flag
Boolean isProcessed = false;
Integer retryCount = 0;
// While the record is not processed and we have not retried more than 5 times
while (!isProcessed && retryCount < 5) {
// Simulate checking the external system (dummy condition for this example)
isProcessed = checkExternalSystemForProcessing();
// If not processed, wait and then retry
if (!isProcessed) {
retryCount++;
System.debug('Waiting for processing... Attempt ' + retryCount);
System.sleep(2000); // Wait for 2 seconds before retrying
}
}
if (isProcessed) {
System.debug('Record processed successfully.');
} else {
System.debug('Failed to process the record after 5 attempts.');
}
In this example, the WHILE
loop checks if a record has been processed by an external system. If it hasn’t, the loop waits and retries up to 5 times. The loop terminates either when the record is processed or when the retry limit is reached.
3. DO-WHILE Loop
The DO-WHILE
loop is similar to the WHILE
loop, but the key difference is that the condition is evaluated after the loop’s code block is executed. This means the code inside the loop will always execute at least once, even if the condition is false
initially.
Syntax:
do {
// Code to be executed
} while (condition);
- Condition: The loop checks the condition after executing the loop’s body. If the condition is
true
, the loop continues; otherwise, it stops.
Example:
Let’s say you want to create a loop that generates a random discount between 5% and 15% and applies it to an invoice, but the discount should only be applied if it’s more than 10%. The loop continues generating and applying the discount until the condition is met.
// Simulated invoice
Invoice__c invoice = [SELECT Id, Amount__c FROM Invoice__c LIMIT 1];
Decimal discount = 0;
// Do-While loop to ensure a discount greater than 10% is applied
do {
// Generate a random discount between 5% and 15%
discount = 0.05 + (Math.random() * 0.1);
System.debug('Generated Discount: ' + (discount * 100) + '%');
// Apply the discount
invoice.Amount__c = invoice.Amount__c * (1 - discount);
} while (discount <= 0.10);
System.debug('Final Discount Applied: ' + (discount * 100) + '%');
update invoice;
In this example, the DO-WHILE
loop generates a random discount and applies it to the invoice. If the discount is less than or equal to 10%, the loop continues generating and applying a new discount until a value greater than 10% is achieved.
Conclusion
Loops in Salesforce Apex (FOR
, WHILE
, DO-WHILE
) are powerful tools that allow developers to repeat code execution based on conditions. The FOR
loop is ideal when the number of iterations is known, the WHILE
loop is useful for indefinite iterations based on a condition, and the DO-WHILE
loop ensures that the code block runs at least once before checking the condition. Each loop type has its own use cases, making them versatile in handling various scenarios in Apex development.