Hadi
Hadi

Reputation: 574

What is the difference between these if statements?

What is the difference between these conditional statements?

if ((middleOfTabIndicator < index * tabIndicatorWidth)) {
    if (index - 1 != featuredTabIndex) {
        // Do something
    }
}

vs

if ((middleOfTabIndicator < index * tabIndicatorWidth) && ((index - 1) != featuredTabIndex)) {
    // Do something
}

All my variables are int. Aren't these conditions the same? When I write the first condition everything is OK but when I write the second condition the result changes. Why this happens?

Upvotes: 0

Views: 71

Answers (2)

Alexander Petrov
Alexander Petrov

Reputation: 9492

What is common is that both IF statements from your example are unclear and would benefit of externalizing them either with a proper variable explaining their meaning or adequatly named method.

They are different constucts mostly. The first one is using nested IF statement. The second one is evaluating the nested IF statement upfront.

The first construct can cover 2 scenarios. 1)middleOfTabIndicator < index * tabIndicatorWidth && ((index - 1) != featuredTabIndex) 2) when middleOfTabIndicator < index * tabIndicatorWidth && ((index - 1) == featuredTabIndex)

While the second construct can cover oly a single scenario:

middleOfTabIndicator < index * tabIndicatorWidth & ((index - 1) != featuredTabIndex)

In a way construct number 1 is more expresive and covers more cases than construct number two. But at the same time you can epress the construct number 1 without nested IF the following way:

if ((middleOfTabIndicator < index * tabIndicatorWidth) && ((index - 1) != featuredTabIndex)) {
    // Do something
}
else if (middleOfTabIndicator < index * tabIndicatorWidth) && ((index - 1) == featuredTabIndex)) {
}

Now you have same behaviour as construct number 1 without nesting.

Upvotes: 1

BeGiNer
BeGiNer

Reputation: 23

In first condition you have "nested if" which means that your "outer if" is checked first then if it is true then your "inner if" (which is nested if) will be checked. In second condition there is only one " if " but it contains two conditions and they both should be true so that if body can run.

Upvotes: 1

Related Questions