Given a scenario, use and apply Apex control flow statements.
These are technical notes I compiled while studying using Focus on Force, a company that provides Salesforce training and certification prep services.
After studying this topic, you should be able to:
- Describe what control flow statements are in Apex and why they are used.
- Identify the different types of control flow statements such as if-else, switch, and loop statements.
- Determine which control flow statements to use in a given a scenario to meet requirements.
Table of Contents
- Conditionals
- Loops
- Break and Continue Statements
- Switch Statements
- Scenarios and Solutions
Introduction
- Apex control flow statements include conditional statements, procedural loops, and switch statements
- Conditional statements:
- If statement
- If-Else statement
- Else-If statement
- Procedural loops:
- Traditional For loop
- List/Set Iteration For loop
- SOQL For loop
- While loop
- Do-While loop
- Conditional statements:
Conditionals
- If statement
if (num >= 100000) {
x = 1;
System.debug('Value of x:' + x);
}
- If-Else statement
if (num >= 1000000) {
x = 1;
System.debug('Value of X: ' + x);
} else {
x = 0;
System.debug('Value of X: ' + x);
}
- Else-If statement
if (num >= 1000000) {
x = 1;
System.debug('Value of X: ' + x);
} else if (num >= 500000) {
x = 2;
System.debug('Value of X: ' + x);
} else {
x = 0;
System.debug('Value of X: ' + x);
}
Loops
- Loops repeat a sequence of instructions until a specific condition is met. 5 types:
- Traditional for loop
- List/Set iteration for loop
- SOQL for loop
- while loop
- do-while loop
- Traditional for loop
- Initialization, check exit condition, increment
// initialization, exit condition, increment
for(i = 0, z = 0; i < 100; i++) {
z = z + i;
System.debug('Value of z: ' + z);
}
- List/Set iteration for loop. Considerations:
- Not writable: not possible to modify a collection’s elements while iterating through it
- Not possible to add or remove elements while iterating through it
- Temp variable: however, elements can be added to a temporary list, set, or map, and then added or removed to or from the original after the loop execution ends
List<Integer> numbers = new Integer[]{1,2,3};
for(Integer num: numbers){
System.debug(num);
}
- SOQL for loop. Considerations:
- Data type of the variable should be the same sObject type of the records returned by the SOQL_query
- Query results are processed in batches of 200 or one record at a time, depending on variable data type used
// One record at a time
for (Contact result : [SELECT LastName FROM Contact LIMIT 3]) {
System.debug('single record: ' + result.LastName);
}
// 200 records at a time
for (List<Contact> results : [SELECT LastName FROM Contact]) {
System.debug('batched records ' + results.size());
}
- while loop
- Can be skipped if the loop condition returns false on initial execution
while (j < 100) {
System.debug('Value of j: ' + j);
}
- do-while loop
- Always executes at least once
Integer count = 1;
do {
System.debug('Value of count: ' + count);
count++;
} while (count < 11);
Break and Continue Statements
- break statements can be used conditionally within a procedural loop statement to exit the entire loop
- When encountered, any remaining loop iteration will not be executed
integer count = 0;
integer j = 0;
Date myDate = date.newinstance(2020, 3, 25);
while (j<100) {
j++;
if (System.today() == mydate)
break;
count++;
}
System.debug('Value of j(number of iterations): ' + j); // 1
System.debug('The count until today: ' + count); // 0
- continue statement can be used conditionally within a procedural loop to skip the current iteration and jump to the next one
- When encountered, current iteration is terminated and next iteration is started
integer count = 0;
integer j = 0;
Date myDate = date.newinstance(2020, 3, 25);
while (j<100>) {
j++;
If(System.today() == mydate){
mydate=date.newinstance(2020, 3, 27);
continue;
}
count++;
}
System.debug('Value of j(number of iterations): ' + j); // 100
System.debug('The count until today: ' + count); // 99
Switch Statements
- Switch statements are used to determine if an expression matches one of several values and branches
- Keyword
when
is used to match values - it can be a single value, multiple values, or sObject types when else
is executed if there is no matching value - it must also be the last block in the switch statement- Nested Switch: possible to nest Apex switch statements to provide multiple execution paths within a when clause
- Keyword
Account a = [SELECT Rating, Status__c FROM Account WHERE Name = 'Edge Communications'];
switch on a.Status__c {
when 'New', 'Prospecting' {
a.Rating = 'Very Cold';
}
when 'Needs Analysis' {
a.Rating = 'Cold';
}
// more when statements
when else {
a.Rating = null;
}
}
update a;
Scenarios and Solutions
A developer needs to query a large number of records from the database for processing. How can the records be queried from the database that it avoids potential heap size error and DML governor limits when updating?
- SOQL for-loop can be used to query results that return many records and avoid the limit on heap size. Each iteration will process records in batches of 200. The break control structure can be used to exit the loop and avoid DML statement governor limit exception.
for (List<Opportunity> results : [SELECT Name, Description FROM Opportunity]) {
System.debug(results.size());
for (Opportunity o : results) {
if (String.isBlank(o.Description)) {
o.Description = 'updated';
// update other fields
}
}
if (Limits.getDmlStatements() < Limits.getLimitDmlStatements()) {
update results;
} else {
break; // exit the loop
}
}
See FoF Slides for more