Baldrick
Baldrick

Reputation: 11002

Java logic AND with IF

I want to perform 4 'if' statements if it can be phrased like that; I want to check four values before something happens. I have put:

if (a==1 && b==2 && c==3 && d==4) {
 foo;
}

Is stacking up logical ANDs like this the preferred method or is four individual IF statements, one inside the other preferred? The logic ANDs method seems much more efficient to me but is the a reason/time/place when they shouldn't be stacked up like this? Or is it always the preferred method?

Upvotes: 0

Views: 1546

Answers (8)

trashgod
trashgod

Reputation: 205785

The conditional-and operator (&&) "evaluates its right-hand operand only if the value of its left-hand operand is true." If the probability of true or false is know in advance, there may be some advantage to changing the order of the predicates.

Upvotes: 1

aioobe
aioobe

Reputation: 420951

Semantically

if (a == 1 && b == 2 && c == 3 && d == 4) {
    foo;
}

is entirely equivalent to

if (a == 1)
    if (b == 2)
        if (c == 3)
            if (d == 4)
                foo;

You choose the one that looks most readable. (Note that if you have many chained conditions, the level of indentation will be terrible if you choose the latter option.)


The only reason to split it up is if you need separate else-clauses:

if (a == 1) {
    if (b == 2) {
        ....
    } else {
        // a == 1, but b != 2
    }
} else {
    // a != 1
}

Upvotes: 5

Ben
Ben

Reputation: 2465

Well it all depends on the specific situation. Stacking them all up in one condition gives you the desired result, but might prove inefficient if this is going to be tested inside a loop or any other code block that is executed really a lot. It is good to partition such a condition to sub conditions (multiple if statements) if this is going to be executed a lot and the probabilities of a, b, c and d having the required value aren't equal. Or if some conditions are more expensive than others (maybe some kind of function calls.

For example, if the probability that a will not equal 1 is very big it is reasonable to put it like this:

if(a == 1)
   if(...)

The compiler does not know about probabilities or how much expensive is a specific call, so it's up to you to decide whether or not it is important to optimize the condition. For instance if you are performing some kind of a heuristic search and this is the condition that goal is reached, then partitioning your condition can give you quite decent performance boost.

If you know for sure that this part of code won't be used often, then definitely go for one condition, because code readability is far more important than a couple of nanoseconds.

Upvotes: 0

maaartinus
maaartinus

Reputation: 46392

In your example the best solution is just what you did. Nesting a lot of ifs is a code smell. Don't care about the speed it'll surely be the same, the JIT takes care about such trivial optimization. Care about readability.

With other things the same, the shorter expression is the better readable one.

Upvotes: 1

Federico klez Culloca
Federico klez Culloca

Reputation: 27119

Maybe you could could wrap that conditions in a boolean for compactness of the if condition

boolean condition = (a==1 && b==2 && c==3 && d==4);

if(condition)
{
    foo;
}

Upvotes: 2

Sergei Tachenov
Sergei Tachenov

Reputation: 24869

The most readable way is the preferred one. In this particular abstract example one if is certainly more readable. Here is an example when it is preferred to use several ifs:

if (someObject != null) {
  if (someObject.getType() == SomeClass.SomeType) {
    // do something
  }
  // maybe more code working with someObject here, much later
}

Not only you can see that these checks are clearly separate things (and you don't mess with the order of checks), but it is also possible to add more code doing something to someObject after the inner if right away.

As for the efficiency, not only you shouldn't even think about it until you have a problem with performance and profiling shows that this is exactly the source of the problem, but also it is most certainly identical in both cases. The compiler probably optimizes both forms into the same code.

Upvotes: 3

irreputable
irreputable

Reputation: 45433

whichever is more readable and understandable.

the following code

if(A)
    if(B)
        do something;
// no else

could be more understandable than if(A & B), depending on the problem.

Upvotes: 3

Alnitak
Alnitak

Reputation: 339796

If the action is required if and only if all four conditions are true, then this is exactly the way to write it.

Upvotes: 3

Related Questions