Grzegorz Gajos Grzegorz Gajos - 4 months ago 10
Java Question

Why 'condition && statement()' is not popular in Java world?

I've been doing Java development for an almost decade now and I've never seen an expression like [2] (see below). I've seen this first time in one of javascript library where it was used a lot.

1.

if(isValid) {
statement();
}


2.

isValid && statement();


The outcome of [1] and [2] is identical as the
statement()
is not going to be evaluated
if isValid == false
.


  • Why syntax like [2] is not popular? I mean, I literally never encounter this before in any Java project I've seen.

  • Are there any implications of approach [2]?

  • Is it considered to be harmful?

  • Are there any surprises I've might come along using this as the alternative for simple
    if
    statements?

  • Does it decrease readability?



Edit:

I was testing this in
Groovy
console. I guess it invalidates this question quite much. Thanks for the responses anyway :).

Answer

if( isValid && statement() ) only works if statement() returns a boolean otherwise the condition wouldn't be compilable. Doing that might not be considered good design (depends on what statement actually does) and might reduce readability or your ability to use the return value of statement().

Besides that just isValid && statement(); isn't supported by the language - and don't make the mistake to compare a language like Java to a language like JavaScript, they follow different paradigms.

You could do something like boolean b = isValid && statement(); but you'd normally only do that if you want to use the value of b somehow.

Comments