Two separate ‘if’ statements in one Apex method

I’m fairly new at Apex and have two fields that need to be set based on different criteria. I want both sets of If/Else to run, but based on looking at examples I am suspicious that maybe the second if might be hanging off the first one. Can I make sure both run somehow?

A related question — I think I have learned that I can’t just make them two methods and call them both in the action parameter of the actionSupport. Right?

Here’s the code. Assume, please that all my fields are defined, etc. because I’ve checked that part a million times. 🙂 There’s a comment below showing where the two should be considered separate.

public pagereference MealFormatChange1() {
    if (dummyMeal.Form__c=='Sack' || dummyMeal.Form__c=='Cooler' || dummyMeal.Form__c=='Box') {
        dummyMeal.Meal_Location__c = DEFAULT_SACK_COOLER_LOCATION;
    } else  {dummyMeal.Meal_Location__c = DEFAULT_MEAL_LOCATION;}

    // Second, separate IF clause starts here
    if (dummyMeal.Type__c == 'Breakfast') {
        dummyMeal.Meal_Time__c = DEFAULT_BREAKFAST_TIME;
    } else if (dummyMeal.Type__c == 'Lunch') {
        if (dummyMeal.Form__c=='Sack' || dummyMeal.Form__c=='Cooler' || dummyMeal.Form__c=='Box') {
            dummyMeal.Meal_Time__c = DEFAULT_SACK_COOLER_LUNCH_TIME;
        } else { dummyMeal.Meal_Time__c = DEFAULT_LUNCH_TIME;}
    } else if (dummyMeal.Type__c == 'Dinner') {
        dummyMeal.Meal_Time__c = DEFAULT_DINNER_TIME;
    }
    return NULL;
}

Answer

Yes, they’re two separate sets of branch logic. You’ve written the code correctly.

If-then logic look like this:

if ( condition ) { expression-or-block } [ else { expression-or-block } ]

Your whitespace might be confusing you a bit, but you can definitely see that your first if statement follows the form perfectly.

For future reference, you should try to write your statements like this:

if(condition) { // This is on its own line
    do-when-true;
} else {  // This is also on its own line
    do-when-false;
}

And for chained if statements (as your second one is):

if(condition-1) {
    do-when-true-1;
} else if(condition-2) { // This should be its own line, too
    do-when-true-2;
} else {
    do-when-false;
}

Fixing your whitespace will help you determine how the logic flows.

As an aside, you’ll notice that I said you can use an expression. That means it’s legal to write:

if(condition)
    do-when-true;
else
    do-when-false;

But remember, you only get one statement, so this would be an error:

if(condition)
    do-when-true-1;
    do-when-true-2; // this will actually run regardless.

It’s best to avoid doing that by explicitly using blocks ({ through } is a block, and they can be contained inside each other).

Attribution
Source : Link , Question Author : JeanneB , Answer Author : sfdcfox

Leave a Comment