Cooking With Code: Conditional Statements in Apex (and Java)

blog-conditional-IntroLately I’ve covered some pretty dense topics (SOQL, For Loops, Apex Collections), so I wanted to lighten up our code batter.

Today, we’ll tackle something on the more airy side and also something super fun to work with (and really handy for all Awesome Admins to know). Welcome to code kitchen, where we’ll whip up a batch of conditional statements!

What is a Conditional Statement?

A conditional statement is a coder’s way to ask a question, and depending on the answer, do one thing or another.

You have probably used conditional statements in your Admin work, but maybe didn’t realize what they were. There are two places that Awesome Admins use conditional statements with point-and-click Salesforce administration:

  • Any time you set up a criteria for any kind of automation (e.g., workflow rules, process builder, visual workflows, approvals process, etc.). This is where you would say, “IF this, that, and the other thing are true, THEN run this process.”
  • Any time you use the IF or CASE functions (e.g., in formula fields, advanced workflow rules, etc.). These are full-blown, in-your-face conditional statements.

Conditional statements are best understood as:
IF X is true, THEN do Y, otherwise (ELSE) do Z.

In Apex, these types of conditional statements are called IF-ELSE statements (the same type of statement in Java is called IF-THEN-ELSE). But before we dive into how Apex does things, let’s look at something more familiar to us as admins … how we use a simple conditional statement/function in a formula field.

How to Use Conditional Statements in Apex

Using IF Functions in a Formula Field

If we created a formula field in our much-beloved custom Recipe__c object to categorize each recipe based on how long they take to prepare, we could use the following IF function syntax:

IF(stateABusinessLogicTest, ifTrueUseThisValue, ifFalseUseThisValue)

So thinking of what we want to achieve, let’s fill in the three placeholder bits to this conditional statement:

Part of Function Description Example
stateABusinessLogicTest This is the test used to decide what value to use. It will either evaluate as TRUE or FALSE. totalTime >= 2
ifTrueUseThisValue This is the value we want the field to hold if the logical test (or condition) is TRUE for that record (e.g., for our example, if the total time to prepare and cook is equal to or greater than 2 hours). Special Occasion
ifFalseUseThisValue This is the value we want the field to hold if the logical test (or condition) is not true (i.e., FALSE) for that record (i.e., the total time is less than 2 hours). Quick & Easy

Below is what the function would look like in the Advanced Formula field builder:

blog-conditional-IFFunction

Using IF-ELSE Statements in Apex

Let’s look at how to set up something similar in Apex. The placeholder bits have different names, but they mean the same thing. The basic syntax of the IF-ELSE condition in Apex is:

if (boolean_condition) {
     // statement_if_true
   } else {
     // statement_if_false
}

Again, filling in the placeholders we have the following:

Part of Statement Description Example
boolean_condition This is the test used to decide what value to use. It is equivalent to the “logical_test” in the IF formula. The reason why it’s called a Boolean Condition relates back to our blog post on Primitive Data Types; Boolean variables can only ever be TRUE or FALSE* totalTime >= 2
statement_if_true This is the code we want to run if the condition is TRUE (e.g., for our example, if the total time to prepare and cook is equal to or greater than 2 hours). system.Debug(‘Special Occasion’);
statement_if_false This is the code we want to run if the condition is FALSE (e.g., if the total time is less than 2 hours). system.Debug(‘Quick & Easy’);

* Technically they can also be NULL, but that’s overly complicating things, so we’re going to ignore that for now. Hey…it’s my blog post and I can do whatever the heck I feel like. <wink>

Our final code would look like this:

blog-conditional-simpleIf

In real life I’d be pulling the totalTime value from my database, but I wanted to keep things simple … go with me on this.

So what you see on line 1 is that that we’ve declared a Decimal** variable (totalTime) and set its value to 2.5. When we run our code, the condition, “Is variable totalTime greater than or equal to 2?” will evaluate to TRUE, and therefore the first block of code will run, resulting in this:

blog-conditional-simpleIfResults

** In case you’re wondering why we declared totalTime as a Decimal variable instead of an Integer variable, this is because Integers can only be whole numbers, while Decimals (or Doubles) can have a decimal point value. For more on this, check out my post, Primitive Data Types in Apex and Java.

If we had set totalTime to equal 1.5 (or really anything less than 2), then the condition would be FALSE and the debug log would have printed a debug line of “Quick & Easy“.

One difference between the declarative version of the IF function and the Apex IF-ELSE version is that Apex doesn’t actually require the ELSE part of the statement. That means, that you could have choose to run code if the statement is TRUE, and do nothing if it is FALSE.

So the following two code snippets are functionally the same:

Snippet #1 (without ELSE) Snippet #2 (with an empty ELSE)
Decimal totalTime = 2.5;
if(totalTime >=2){
  system.debug('Special Occasion');
}
Decimal totalTime = 2.5;
if(totalTime >=2){
    system.debug('Special Occasion');
  }else {
    // nothing happening here
} 

As we know, I generally go for less typing so, no surprise here, I prefer the first version.

Ternary Conditional Operations

Want to see something really cool? (Hell Yeah!)

If we’re only dealing with a simple IF-THEN-ELSE statement, then we can shorten things even more using something called a Ternary Conditional Operation, which contains the entire conditional statement in one super compact line:

boolean_condition ? statement_if_true : statement_if_false

So we could change our code to:

Decimal totalTime = 2.5;
system.debug(totalTIme>=2 ? 'Special Occasion' : 'Quick & Easy');

How’s that for short and sweet!? Way short and super sweet!

But what would happen if we wanted to have more than two options, or if the criteria was a little more complicated than this? Let’s take a look at how we would handle that in Apex.

Advanced-Beginner IF-ELSE Statements

We want to get a little more sophisticated in our conditional statement. As you can imagine, just because something doesn’t take much time to make, doesn’t mean it’s particularly easy to make. What about those recipes that take less than two hours, but are pretty complicated and require mad cooking skills? What we need here are some additional categories, which will involve more than just one criterion.

Let’s check that out …

First, let’s look at our categories and what would qualify a recipe to fall into them:

blog-conditional-Minestrone

Category Criteria Example
Special Occasion Take a long time to prepare and cook (over 2 hours) and are not easy to make Baklava
Slow Sunday Take a long time to prepare and cook (over 2 hours) but are easy to make Minestrone Soup
Quick Challenge Take a short time to prepare and cook (30 minutes or less) but are not easy to make Coeur a la Creme
Quick & Easy Take a short time to prepare and cook (30 minutes or less) and are easy to make Grilled Cheese
Middle-o-the-Road Everything that doesn’t fit into the categories above Chocolate Chip Cookies

We’re going to see a few different ways to write this, and at the same time, show you how to nest IF-Else statements.

Take One – The FLAT Version

The first version of code I’m going to show you is the most literal translation of the categories above.

For each of the rows above, we have a separate conditional statement. You can see that we’re using the ELSE IF clause, to specify additional conditions and subsequent code to run if they evaluate as TRUE.

If I were to write this out in pseudo code, it might say something like:

// If the total time is greater than or equal to 2 AND the difficulty isn't 'Easy" then it's a Special Occasion.
 // Otherwise (ELSE), if it's 2 hours or more and easy = 'Slow Sunday'
 // Otherwise (ELSE), if it's 30 mins or less and NOT easy = 'Quick Challenge'
 // Otherwise (ELSE), if it's 30 mins or less and easy = 'Quick & Easy'
 // Otherwise, everything else = 'Middle-o-the-Road'

In Apex, it would look like this

Decimal totalTime = 2.5;
String difficulty = 'easy';

IF (totalTime >=2 && difficulty != 'easy'){
      //do this if long and not easy
      system.debug('Special Occasion');
  } ELSE IF (totalTime >=2 && difficulty == 'easy') {
      //do this if long and easy
      system.debug('Slow Sunday');
  } ELSE IF (totalTime <= 0.5 && difficulty != 'easy') {
      //do this if short and not easy
      system.debug('Quick Challenge');
  } ELSE IF (totalTime <= 0.5 && difficulty == 'easy') {
      //do this if short and easy
      system.debug('Quick & Easy');
  } ELSE {
      //do this if none of the above applies
      system.debug('Middle-o-the-Road');
}

This example describes one of my favorite recipes, Minestrone Soup, a perfect Slow Sunday recipe! This is perfectly legitimate code, but as many things in coding, we have options. Let me show you another way to work your IF-ELSE statements … by nesting them.

Take Two – The NESTED version

blog-conditional-flow-nested-thumbYou may have noticed there is some redundancy in our code above; we have two lines that have conditions that include the total time >= 2 and two lines where the condition includes total time <= 0.5.

Again, there is nothing wrong with this, but let’s try this another way, this time using nested IF-ELSE statements.

Just like when you nest IF functions in a formula field, you can also nest IF-ELSE statements in Apex.

Decimal totalTime = 2.5;
String difficulty = 'easy';

IF (totalTime >=2){
   IF (difficulty != 'easy'){system.debug('Special Occasion'); }
      ELSE {system.debug('Slow Sunday');}
   } ELSE IF (totalTime <= 0.5) {
      IF (difficulty != 'easy'){system.debug('Quick Challenge'); }
         ELSE {system.debug('Quick & Easy'); }
   } ELSE {system.debug('Middle-o-the-Road');
}

Which Version Should You Choose?

blog-conditional-nestedSo great! We have options … but why would you use the flat version versus nested? To some extent it’s a matter of style and personal preference. The first version (flat) is easier to read, but there are some minor processing speed advantages of both of them, under different situations.

For example, if we were to run both pieces of code with the following settings:

Decimal totalTime = 2.5;
String difficulty = 'hard';

Then the flat version would only need to process through the first decision node, to know what code to run; the nested version would need to process through at least two decision nodes.

However, what if you had larger code segments that would run any time the totalTime was 2.5 or higher. In the flat version, you’d need to repeat this code in every section that related to that length of time. Not very efficient. Also, if you need to make a change to the code, you’d need to replicate that change in all the different places you had the repeated code. Again, not efficient!

This, then, would make our code a good candidate for the nested version of the IF-ELSE statement. Then you have only one place to put this code, and therefore one place to manage. Much better!

So, as you can see, there are no hard and fast rules on which version (flat or nested) to use. Personally, I tend to default with the flat version, because it’s easier to read, unless something in my code that speaks to the nested version (e.g., repetitive sections of code).

Wrapping Up

I hope you’ve had a fun time cooking up some conditional statements in our coding kitchen. I also hope that you see you are just a short hop from the declarative dining room into the exciting world of the coding kitchen.

After reading this post, we know IF-ELSE statements in Apex:

  • Are functionally very similar to using IF functions in formula fields.
  • Use one or more Boolean conditions that if evaluate to TRUE run code.
  • Can have just one condition, or a string of conditions (ELSE IF conditions).
  • Can nest IF-ELSE statements.
  • Can include code in an ELSE statement that will run if none of the IF or ELSE IF statements evaluate to TRUE.

Phew! I hope you found this a light yet satisfying episode of Cooking with Code. Hope to see you again!

Until next time … Bon Appétite!