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?
nested-if: A nested if is an if statement that is the target of another if or else. Nested if statements mean an if statement inside an if statement. Yes, java allows us to nest if statements within if statements. i.e, we can place an if statement inside another if statement.
Nested IFs are powerful, but they become complicated quickly as you add more levels. One way to avoid more levels is to use IF in combination with the AND and OR functions. These functions return a simple TRUE/FALSE result that works perfectly inside IF, so you can use them to extend the logic of a single IF.
Switch statement works better than multiple if statements when you are giving input directly without any condition checking in the statements. Switch statement works well when you want to increase the readability of the code and many alternative available.
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"
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With