Forgot username/password? Don't have an account?
Login with Facebook
Home » Courses » Conditionals 1 - 'if' » Nested if’s – The Answer
Subscribe for updates.
* New to us? log in with Facebook and get a free day pass

Nested if’s – The Answer

A different approach to the

“MBX channel Slide rendering scenario”

We discussed in the last summary for nested-if constructs that we could apply them for 2 independent categories of checks for classification, labeling, or whatever weneed to automate. Since the criteria for categories are independent of each other, we could invert the levels of nesting. In plain language, it means that the condition(s) that we were checking inside the outer if-else clause are now promoted to the outer level, and vice-versa.

In the context of the scenario of the previous summary, the MBX channel slide-rendering problem: we now first broadly check for the weather, and then classify the background color according to the actual time of day.

The logic for this implementation of logic would look something like:

“If the weather outside is Good, then

If the time currently is daytime, then set background color to Sky-Blue. Otherwise, set the background to Pitch-Black.”

“Otherwise, if the weather outside is gloomy,

If the time is currently daytime, then set background to Gray-Blue. Otherwise, set it to Dark-Gray.”

The pseudo-code for this application would look something like:

if(weather == “good”) {

if(time == “daytime”) {

Background = “sky-blue”;

}else {

Background = “pitch-black”;

}

}else {

if(time == “daytime”) {

Background = “gray-blue”;

}else {

Background = “dark-gray”;

}

}

Depending on the number of categories in each classification method, we can intuitively decide for ourselves which classification is nested outside, and which is surrounding the other. A good rule of thumb to make the code more readable, would be that “Have the category that has more conditionals on the outer level, and the other category (with fewer conditionals) nested inside the former.” But the decision is left to the programmer’s discretion, since the logic of the program could dictate otherwise.

In general, there could be more than 2 categories to check for, so there is NO hard-and-fast rule or trick to find the “best” nesting order. But you will develop your own style and flare over time and with enough practice!

Got A Question?

'I love being Prime'

Have a question but don't want to ask it publicly? If you are a prime member just ask right here and we will get back to you within 48 hours. Not prime yet? no worries you can ask publicly below.

Act now while we have available seating

Our on line school is private, affordable and interactive with trainer support.
Act now save your seat before someone else takes yours.
Act now