4.3 Nested if statements

The concept

If/else statement can be used inside another if/else body. Let’s reopen our Commodity class and modify it.

public class Commodity 
{
    public Decimal price;
    
    public Boolean purchaseDecision(Integer willingPower)
    {
        Decimal discountedPrice;
        if(price < 100) 
        {
            return true;
        }
        else 
        {
            discountedPrice = price * 0.7;
            
            if(discountedPrice < 150 && willingPower > 3) 
            {
            	return true;    
            }
            else if(discountedPrice < 300 && willingPower > 5)
            {
                return true;
            }
            else if(willingPower > 10) //No matter what, I want it
            {
                return true;
            }
            else 
            {
                return false; 
            }
        }
    }
    //...
}

Try call this method in your anonymous block and see the result.

A bit explanation

One thing which might be a bit different here is now we see a function can actually return (finish) in the middle of the function, instead of at the end of it. A function can actually return at any point of a function. But usually it is at the end of a function or in an if/else statement. Otherwise, the following code won’t make much sense.

Other than that, the grammar is not very different. Read the code and think a bit more about how to construct and write similar code. This is the building block for the all the more complicated programming.

Exercise

Write a bit more about nested if/else here. Without the loop which we will introduce in next chapter, you code here won’t be too complicated. But still, I guarantee you the more you practice here and in next (loop) chapter, you will find life easier in your developer’s life. So do practice a bit about if/else statements here and do more practice after we finish the next chapter.

Next Post

5.1 A quick introduction to List in Salesforce

Subscribe to Sfdcinpractice

Subscribe to get the latest blogs and tutorials of sfdcinpractice. No spam, no trash, only the awesome posts from sfdcinpractice. 

Leave a Reply

Your email address will not be published / Required fields are marked *