As developers, we aim to write code that is efficient, maintainable, and scalable. One way to achieve this is by following the DRY principle. Loops are a powerful tool that can help us avoid duplicating code and keep our programs concise. By using a loop to repeat a task based on a condition, we can write flexible code.
Let's look at a simple example to understand when to use loops. Say there is a method named calculateSum()
responsible for accepting a list of integers and returning the summation of those integers:
public Integer calculateSum(List<Integer> numbers){ Integer sum = 0; sum += numbers[0]; sum += numbers[1]; sum += numbers[2]; sum += numbers[3]; return sum; }
The method could be called 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. So should we add as many indices as we can just in case?
public Integer calculateSum(List<Integer> numbers){ Integer sum = 0; sum += numbers[0]; sum += numbers[1]; sum += numbers[2]; sum += numbers[3]; sum += numbers[4]; sum += numbers[5]; return sum; }
Nope! We shouldn't do that either. This approach works when there are exactly 6 elements:
List<Integer> numbersToSum = new List<Integer> {5, 10, 2, 3, 100, 200}; Integer sumOfIntegers = calculateSum(numbersToSum); // sumOfIntegers is 320
But we're in BIG trouble when there are fewer than 6:
List<Integer> numbersToSum = new List<Integer>{5, 10, 2, 3}; Integer sumOfIntegers = calculateSum(numbersToSum); // System.ListException thrown!!
The calculateSum()
method is trying to access the 4th and 5th indices which don't exist. This causes the System.ListException: List index is out of bounds: 4
runtime error.
Writing code that relies on fixed indices is not scalable and can cause unexpected errors when the input size changes. Using loops is a better approach to handle varying input sizes. We'll show you how to write dynamic code that can scale as the input size changes with loops in this course.
Note: In this course, we'll use two types of notations to reference a list:
Using the List
keyword:
List<Integer> numbers = new List<Integer> {1, 2, 3};
or by using the array notation:
Integer[] numbers = new Integer[] {1, 2, 3};
The outcome is the same, it's just different syntax. Good luck with the course and your coding journey. Please don't hesitate to provide feedback or advice if you have any!