APEX: LOOP CYCLES

A Quick Guide on FOR Loops

Apex is Salesforce’s proprietary cloud-based, object-oriented programming language. Let’s break down that a little bit:

  • Apex was built by Salesforce, for Salesforce. You will not be able to write and run Apex outside your Org.
  • Apex is cloud-based. Unlike many other programming languages, you do not need to install any software to start developing in Apex nor will you have to compile it because the platform will take care of that for you.
  • Apex is object-oriented. In Apex, you can create blueprints with attributes and procedures that you can later instantiate into objects.

The truth is, Salesforce’s programming language shares a lot in common with other well-known object-oriented languages, like Java or C#. I would even say that they are nearly 80% similar, however it’s that last 20% that might get you into trouble if you don’t carefully understand the differences.

For example, one common task all programming languages have is how to address procedural cycles — this is when the same process needs to happen to each element of a collection. In the software development world, we address this challenge by using an iteration loop. Apex has six types of loops:

  1. do-while
        do {statement(s)}
        while (Boolean_condition);
  2. while
        while {Boolean_condition) statement(s);
  3. traditional FOR
        for (initialization; Boolean_exit_condition; increment)
        {
        statement(s);
        }
  4. List/Array FOR
  5. SOQL FOR
  6. List SOQL FOR

The first three of them are shared among many, if not all, programming languages. I’ll assume that you are very familiar with them, but if you’d like more info check out this site. The last three, on the other hand, are Apex-specific iteration procedures.

Understanding Apex FOR Loops

Let’s look at each Apex-specific loop to understand their strengths and weaknesses.

List/Array FOR Loop

Here is a simple scenario: A web service returns the name of each month left in the current year. In Apex, you need to iterate over the loop and append the year to each month’s name.

List<String> monthsLeft = new String[]{‘January’, ‘February’, ‘March’, ‘April’, ‘May’, ‘June’, ‘July’, ‘August’, ‘September’, ‘October’, ‘November’, ‘December’};
for(String month : monthsLeft)
{
      month  +=’   ‘+system.Today ( ) .year ( ) ;
      system.debug (month) ;

}

Quite straightforward, right? It iterates over each element of the list, and executes the statements inside the curly brackets.

You can use this FOR  with any type of List or Set as long as the inner variable matches the type of value in the list.

SOQL FOR Loop

What if the information you want to iterate over is stored in the database? Say for example you want to update the Phone field of all Contacts associated with an Account named “Acme Inc”. Without this type of loop, the steps involved would include: query the records from the database, store them in a List, and then use an List/Array FOR. It would look something like this:

However, using SOQL FOR Loop looks like this:

  1. Notice how we use a SOQL statement inside the FOR definition, hence the name “SOQL FOR Loop”.
  2. Between the curly bracket we perform the update to the field in memory, and add the update record to a list of contacts
  3. Finally, outside the loop we perform the DML statement to update the records in the database. (DML stands for Data Manipulation Language, these are the actions you perform in the database such as: update, insert, delete, etc.)

Remember when we mentioned that Apex is 20% different from other programming languages? Well, most of the difference you will encounter while developing with Apex are based on the limits the platform enforces. These are known as Governor Limits.

When we we talk about Governor Limits and loops, there are two rules of thumb:

  • Never perform a SOQL Statement inside a loop
  • Never perform a DML Statement inside a loop

The reason behind this is that both SOQL and DML statements have a very low limit per transaction — 150 and 100 respectively. That’s why as a Salesforce Developer you must carefully craft your code in such a way that plays nicely with the Governor Limits.

List SOQL FOR Loop

This is my favorite type of FOR Loop. It’s a heavyweight champion and I use it every time I know that more than a thousand records will need to be iterated over.

Here is the scenario: there is a new picklist field on the Opportunity object called Audit_Status__c and the Head of the Sales department wants you to set the field to “Completed” for all Opportunities that created within the last 5 years. You know that there are around 20,000 Opportunities that meet this criteria.

Here is how to do it:

  1. When the iterating variable of a FOR Loop is a List<anyType> and the iterating set is a SOQL statement, the platform will automatically batch your SOQL statement and will return the records found by your SOQL in batches of 200 records. In this scenario, the inner variable called oppList will always have at most 200 opportunities per batch iteration.
  2. Once you have 200 opportunities in the oppList variable, then you use a List/Array FOR Loop to go over each element of the list and perform the update to the field in memory.
  3. Finally, you execute the DML statement to effect the change on the database.

But Wait! What about the “Never perform a DML statement inside of a FOR Loop” rule? Well, if you look closely, you are not performing the DML statement inside of a List/Array FOR Loop block (denoted by the green solid lines), you are actually performing it right outside the List/Array FOR Loop, but inside the List SOQL FOR Loop.

This type of FOR Loop also helps with the Governor Limit that restricts the number of records affected by a DML statement to 15,000. If you were to solve this business scenario with an SOQL FOR Loop like this:

You will get a DML error stating that you are performing an update on more than 15,000 records in a single transaction.

Now you’ve got a basic understanding of the core looping mechanisms that make Apex distinct from other programming languages. Implementing the correct one for your business scenario will help you craft Apex code that can withstand the loads of your application.

 

About the Author

Clara Perez is a Salesforce MVP and Lead Developer at Great Wave who loves teaching Salesforce concepts.