Question

My IDE (IntelliJ IDEA) is telling me that I have the option to remove the braces on this if statement:

if (objectIsOfTypeFoo) {
    if (objectOfTypeFooIsShared) {
        // do something with Object of type Foo knowing that it's shared...
    } else {
        // do something with Object of type Foo knowing that it's not shared...
    }
} else if (objectIsOfTypeBar) {
    ...
}

To become:

if (objectIsOfTypeFoo) if (objectOfTypeFooIsShared) {
    // do something with Object of type Foo knowing that it's shared...
} else {
    // do something with Object of type Foo knowing that it's not shared...
} else if (objectIsOfTypeBar) {
    ...
}

I understand how this makes sense, and it's tempting to lose the indent, but my concern is that readability may suffer. The latter looks cleaner, but is the space saved worth the potential confusion?

I assume the performance difference between the two is trivial, if at all.

And as a follow up question: Is there a limit to how many 'if (condition)'s you can fit in a single line, or rather at what point does it become too many?

Was it helpful?

Solution

I'm voting for the way you already have.

I don't even use this:

if(foo)
   return bar;

I like this instead:

if(foo){
   return bar;
}

"programs must be written for people to read, and only incidentally for machines to execute"

OTHER TIPS

Always use braces. One day, you will want to put a second statement in your if or else block, and then you will wish you had. However, are you really making instanceof checks? Can you rework your program to turn them into polymorphic object behavior instead?

I'd prefer the first one. I think that bit with multiple ifs on a single line is unreadable.

Sorry, but I'm going to vote to close. It'll be a debate without an answer.

It's recommended to always use braces , but is there a situation when no body use braces and it is better not using them cause is more readable

if(condition){

} else if (condition) {
    ...
}else if (condition3){

}

if you always use braces it would be like this .Probably i mistake in some place.

if(condition){

 } else{ 

       if (condition) {
             ...
       }else {

           if (condition3){

           }//end if
       }//end else
 }//end else

So i think that using always depends of readability, like above said programs must be written for people to read and only incidentally for machines to execute.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top