Start tracking your progress
Trailhead Home
Trailhead Home

Control Data Flow

Learning Objectives

After completing this unit, you’ll be able to:

  • List the usages of the comparison operators.
  • Describe the difference between switch and if-else statements.

In our everyday lives, there are always decisions to make. What do I wear? What do I eat? Should I go left or right? The same thing goes when writing code. Think back to our Teatime pseudocode in unit 1, specifically step 2. 

Boil water in a Tea Kettle
Fill Kettle with Water
Switch Kettle On
Wait for Water to Boil

Hmm… everything seems pretty accurate, right? To boil water, I fill the kettle with water, turn the kettle on, and wait for the water to boil. But what if there’s already some water in the kettle? What if the kettle is full? How long should the water boil?

Expressions and Expression Operators

Before we make decisions, we often make comparisons. Is this larger than that? Is this equal to that? Developers often compare values before making decisions in their applications. In code, we compare two expressions by placing an expression operator between them. 

An expression is a snippet of code that, when evaluated, results in a single value. For our purposes in this module, an expression might be a literal value (such as 12), or a variable (such as numberOfTeaCups), or a mathematical operation (such as 7 x 4).

Expression operators compare or show equality between two values. A comparison statement consists of two expressions separated by an expression operator, and produces a Boolean value, either true or false. 

Comparison Operators

Operator
Description
Syntax
Result
<
Less than
1 < 2
TRUE
<=
Less than or equal to
1 <= 2
3 <= 3
TRUE
==
Equal to
10 == 10
TRUE
!=
<>
Not equal to
10 != 0
10 <> 11
TRUE
>
Greater than
11 > 10
TRUE
>=
Greater than or equal to
40 >=10
40 >= 40
TRUE

Why does the Equal to operator have two equals signs? Remember that we used a single equals sign in this statement:

Integer i = 2;

One equals sign ( = ) is an assignment operator. It assigns values. Two equals signs ( == ) is a comparison operator. It compares two values to determine whether they are equal (true) or not equal (false).

Operators are particularly helpful when you want to compare a known value with a variable, or compare the values of two different variables. 

Integer numberOfTeaCups = 2;
numberOfTeaCups == 3;  //false
numberOfTeaCups == 2; //true

We’ve seen an example of an integer variable and a string variable. We can also create a Boolean variable that holds the result of a comparison. Check this out:

Integer numberOfTeaCups = 2;
Boolean result = numberOfTeaCups > 3; // 2 > 3 = false

Line 1 sets the numberOfTeaCups variable to 2.

Line 2 creates a Boolean-type variable named result, compares the numberOfTeaCups variable value to the number 3, and assigns the result of the comparison (false) to the result variable. 

Although comparisons are helpful for determining how one thing relates to another, where they really shine is within conditional statements, where they help make decisions.

Conditional Statements

Developers use expressions within conditional statements to create decision-making structures that specify one or more conditions to be evaluated or tested by the program. Wow, that was a mouthful. Let’s break that down.

A conditional statement sets up two or more options. If you’ve ever created criteria in Process Builder, you’ve used a conditional statement. For example, “if state equals California, then display records in the list view” is a conditional statement. “State equals California” is the  condition, and “display records in the list view” is the action the program takes only when the condition is true. In this example, the two options are display records (explicit) and don’t display records (implied).

If-Else Statements
A commonly used conditional statement in Apex is the if-else statement. It looks like this:

if (condition is true){
    //do this
}else{
    //do this
}

Line 1 defines the condition (written in parenthesis).
Line 2 contains the code to run if the condition on line 1 is true.
Line 3 introduces the second option, the else option.
Line 4 contains the code to run if the condition on line 1 is false.

In Apex, we enclose conditional statements within curly braces: { }. When a curly brace is opened, { there needs to be another closed curly brace, } that follows that block of code.

Let’s use a conditional statement in our Teatime pseudocode to check the water level in the tea kettle and decide what to do next based on the water level.

  1. In the Developer Console, click Debug | Open Execute Anonymous Window.
  2. Copy this code and paste it into the Enter Apex Code the window.
  3. String waterLevel = 'full'; /*This variable keeps track of the water level status: full or empty*/
    if(waterLevel == 'empty'){
        System.debug('Fill the tea kettle');
        waterLevel = 'full'; /*Once the tea kettle is filled the variable is changed to full*/
    }else{
        System.debug('The tea kettle is full');
    }
  4. Select the Open log checkbox and then click Execute.
  5. The Execution Log opens, displaying the result of running your code. Select the Debug Only checkbox at the bottom of the window.

On line 1, we initialized the waterLevel variable to full. Generally, the variable values in code are entered by users or derived from other data, not specified within the code itself. In our Teatime example, we would get physical data from sensors in the kettle to determine the water level. When such data is unavailable, developers set values directly in the code (temporarily) so that they can run the code and test it. Setting values in the code is called hard coding. For testing purposes, we hardcoded the waterLevel variable value full. Since that value has already been set, the first if statement (line 2) will never run, because waterLevel will never start out being empty

The code checks to see if the waterLevel variable is equal to empty. Because we hardcoded the waterLevel full, the if statement condition is false. When the if condition is false, the else code block runs. 

Our code currently handles two conditions: water level is full and water level is empty. But those aren’t the only possibilities, right? The kettle might be partially full. How do we handle more than two possibilities? 

If-Else If Statements
To handle more than two possibilities, we use an if-else if statement. The if-else if statement adds another if condition before the final else condition. Let’s look at an example in action.

  1. In the Developer Console, click Debug | Open Execute Anonymous Window.
  2. Copy this code and paste it into the Enter Apex Code window.
  3. String waterLevel = 'half';
    if(waterLevel == 'empty'){
        System.debug('Fill the tea kettle');
        waterLevel = 'full';
    }else if(waterLevel == 'half'){
        System.debug('Fill the tea kettle');
        waterLevel = 'full';
    }else{ /*This statement only runs if line 2 and line 5 result in false.*/
        System.debug('The tea kettle is full');
    }
  4. Select the Open log checkbox and then click Execute.
  5. The Execution Log opens, displaying the result of running your code.Select the Debug Only checkbox at the bottom of the window.

As you test the code, change the value of the waterLevel variable in line 1. The output in the debug log reflects the change. Try all three values: half, full, and empty.

Arrange conditional statements so that the first condition is the most common one. This arrangement reduces the amount of code that runs each time the code block is executed. In our Teatime example, the kettle is most likely to be empty, so we put that condition first. It’s not likely that the tea kettle is full, so we check for that condition last. 

Switch Statements

A more efficient alternative to an if-else  statement is a switch statement. A switch statement specifies a set of values and tests an expression to determine whether it matches one of those values. Here is how it looks:

switch on expression{
    when value1{
        //code block 1
    }
    when value2{
        //code block 2
    }
    when else{ //if none of the previous values apply
        //code block 3
    }
}

In a switch statement, you can have one or more values after the when reserved word. 

switch on expression{
    when value1{ //single value
        //code block 1
    }
    when value2, value 3{ //multiple values
        //code block 2
    }
}

Let’s apply switches to our Teatime pseudocode.

  1. In the Developer Console, click Debug | Open Execute Anonymous Window.
  2. Copy this code and paste it into the Enter Apex Code window.
  3. String waterLevel = 'empty';
    //option 1 using a single value
    switch on waterLevel{
        when 'empty'{
            System.debug('Fill the tea kettle');
        }
        when 'half'{
            System.debug('Fill the tea kettle');
        }
        when 'full'{
            System.debug('The tea kettle is full');
        }
        when else{
            System.debug('Error!');
        }
    }
    //option 2 using multiple values
    switch on waterLevel{
        when 'empty', 'half'{ //when waterLevel is either empty or half
            System.debug('Fill the tea kettle');
        }
        when 'full'{
            System.debug('The tea kettle is full');
        }
        when else{
            System.debug('Error!');
        }
    }
    
  4. Select the Open log checkbox and then click Execute.
  5. The Execution Log opens, displaying the result of running your code. Select the Debug Only checkbox at the bottom of the window.

Logical Operators

You’ve seen how to handle two or more conditions. Now, what do you do when a single condition can be satisfied by more than one value? 

“Or” example:
if (this OR that){
    //do this
}else{
    //otherwise do this
}

 “And” example: 
if (this AND that){
    //do this
}else{
    //otherwise do this
}

The logical operators and and or allow you to write code that checks more than one value to determine whether a condition is true or false. The and operator requires that all values are true to satisfy the condition. The or operator requires that at least one of the values is true to satisfy the condition.

Logical Operators

Logical Operator
Syntax
Description
&& (AND)
X && Y

System.debug(true && true); // true

System.debug(false &&  true); //false

System.debug(true && false); // false

System.debug(false && false); //false
X and Y are Boolean values. If both X and Y are true, then the expression is true. Otherwise the expression is false.
|| (OR)
X || Y

System.debug(true || true);  //true

System.debug(false || true); //true

System.debug(true || false); //true

System.debug(false || false); //false
X and Y are Boolean values. If both X and Y are false, then the expression is false. Otherwise the expression is true.

Let’s try out logical operators. Here’s our code when it was written as an if-else if statement.

String waterLevel = 'half';
if(waterLevel == 'empty'){
    System.debug('Fill the tea kettle');
    waterLevel = 'full';
}else if(waterLevel == 'half'){
    System.debug('Fill the tea kettle');
    waterLevel = 'full';
}else{ //This statement only runs if line 3 and line 6 result in false.
    System.debug('The tea kettle is full');
}

Look at lines 3-4 and lines 6-7. They are identical. We call this redundant code. Eliminating redundancy is a best practice because it makes code more readable and easier to understand, debug, and maintain. Our code performs the same actions whether the waterLevel is empty or half. We can simplify this code by combining empty and half into one condition. We use the or operator so that the condition is satisfied when either value (empty or half) is true.

  1. In the Developer Console, click Debug | Open Execute Anonymous Window.
  2. Copy this code and paste it into the Enter Apex Code window.
  3. String waterLevel = 'half';
    if(waterLevel == 'empty' || waterLevel == 'half'){
        System.debug('Fill the tea kettle');
        waterLevel = 'full';
    }else{ //This statement only runs if line 3 false.
        System.debug('The tea kettle is full');
    }
  4. Select the Open log checkbox and click Execute.
  5. The Execution Log opens, displaying the result of running your code. Select the Debug Only checkbox at the bottom of the window.

Well, look at that. We removed our code redundancy. Using logical operators (&& and ||) is an effective way to remove or reduce redundant code and improve readability.

Keep Your Code Clean

In programming, you often have more than one way to do something. For example, you can use switch statements or if-else statements and arrive at the same result. The important thing to think about when you select a type of statement to use is how each affects the readability of your code. As you continue to work with code, you learn more ways to keep your code clean. For now, focus on making your code easy to read and understand. 

Resources