Why Loops? Moving Beyond "Garbage" Code
As developers, we aim to write code that is **efficient, maintainable, and scalable**. One way to achieve this is by following the DRY (Don't Repeat Yourself) principle.
Loops are a powerful tool that helps us avoid duplicating code and keeps our programs concise. By using a loop to repeat a task based on a condition, we can write flexible code that adapts to any data size.
The Problem: Hard-Coded Indices
Imagine a method named calculateSum() responsible
for accepting a list of integers and returning their summation:
public Integer calculateSum(List numbers){
Integer sum = 0;
sum += numbers[0];
sum += numbers[1];
sum += numbers[2];
sum += numbers[3];
return sum;
}
You might call it like this:
List<Integer> numbersToSum = new List<Integer> {5, 10, 2, 3};
Integer sumOfIntegers = calculateSum(numbersToSum); // sumOfIntegers is 20
⚠️ This code is a hot pile of garbage!
There is no guarantee that numbers will have exactly 4 elements.
It could have 10, 2, or no elements at all.
If we try to access index 4 or 5 when they don't exist, we get the dreaded:
Writing Scalable Code
Writing code that relies on fixed indices is not scalable. Using **Loops** is a better approach to handle varying input sizes. In this course, we'll show you how to write dynamic code that scales perfectly.
List<Integer> numbers = new List<Integer>();
Integer[] numbers = new Integer[]();
Note: Both syntaxes work exactly the same in Apex!
Mastering the For-Each Loop in Apex
A concise method for traversing a list is by using a for-each loop. This loop extracts each item sequentially, enabling us to execute tasks on every element without worrying about manual index numbers.
Standard Structure
for(datatype variable : collection) {
// perform action here
}
Refactoring: Cleaning up calculateSum()
In the old way, we had to manually add every index. It wasn't scalable. If the list grew, the
code
broke.
Replacing the body with a for-each loop
gives us dynamic code that works for any size.
sum += numbers[0];
sum += numbers[1];
sum += numbers[2];
sum += numbers[3];
for(Integer num : numbers) {
sum += num;
}
Note: The loop variable num references each element one by
one
until the list ends, then exits automatically.
💡 Suggest an Improvement