Skip to main content

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 Flow 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: { }. Each opening curly brace ({) must be paired with a closing curly brace (}). When a block of code has an opening curly brace and no closing curly brace, an error occurs.

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.
    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');
    }
  3. Select the Open log checkbox and then click Execute. The Execution Log opens, displaying the result of running your code.
  4. 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 3) 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 options: 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.
    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');
    }
  3. Select the Open log checkbox and then click Execute. The Execution Log opens, displaying the result of running your code.
  4. 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, value3 { //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.
    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!');
        }
    }
  3. Select the Open log checkbox and then click Execute. The Execution Log opens, displaying the result of running your code.
  4. 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?

Logical Operators

Operator OR AND
Operator symbol || &&
Pseudocode If X or Y, do this.
Otherwise, do that.
If X and Y, do this.
Otherwise, do that.
Apex code if(X || Y) {
//do this
} else {
//do this
}

if(X && Y) {
//do this
} else {
//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.

Evaluating 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 4-5 and lines 7-8. 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.
    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');
    }
  3. Select the Open log checkbox and click Execute. The Execution Log opens, displaying the result of running your code.
  4. 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

Keep learning for
free!
Sign up for an account to continue.
What’s in it for you?
  • Get personalized recommendations for your career goals
  • Practice your skills with hands-on challenges and quizzes
  • Track and share your progress with employers
  • Connect to mentorship and career opportunities