Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Since when does if/else require braces? [closed]

Tags:

java

netbeans

I just started a new project in the latest Netbeans, and I noticed it has started giving me code advisories for code like this:

    if (a == null) x = 0;
    else x = 1;

it says

If-Else Statements MUST use Braces

it wants to "fix" it to this:

    if (a == null) {
        x = 0;
    }
    else {
        x = 1;
    }

which I don't want at all. I am particular about this and it makes the code look unnecessarily cluttered. I have tens of thousands of lines of code that don't use (and apparently don't need) the extra braces. Assuming Netbeans has it right, when did this requirement happen and what is driving it?

P.S. I know I can turn off those messages.

UPDATE TO QUESTION:

It might not have been obvious the way that I wrote this, but based on @corsiKa's comments below maybe I should clarify. I really didn't want a discussion of whether the curly braces were or were not desirable. I wanted to know if they have become necessary.

The boys and girls that write and produce Netbeans are usually pretty well plugged in to the community and what direction Java is taking or what is contemplated. So I considered it possible that when they were using the advisory mechanism to give us a heads up that the java grammar is going to change and the code practice that I was using was going to become deprecated at some point.

From saber_raider's answer below it looks like the answer is no. It appears that the Netbeans advisory was overstated with the word MUST as Mystical suggested.

like image 784
AlanObject Avatar asked Sep 13 '12 15:09

AlanObject


3 Answers

That is code advisory. It is always safe to have braces around if/else. Missing braces may create confusion while maintenance.

like image 180
kosa Avatar answered Oct 04 '22 16:10

kosa


This is definitely not a syntactical requirement of java but just a feature of netbeans. Feel free to turn it off if you are sure what you are doing...

like image 34
sabre_raider Avatar answered Oct 04 '22 15:10

sabre_raider


It's an advice after all, not a rule. I've seen many cases in which a lack of brackets made a direct impact on "readability" and maintentance, because an if is only wrapping the next line of code instead of the next two lines, as in this example:

if(condition)
    doSomething();
    condition = false;

condition is always set to false and leads to a bug.

In the particular case you state (variables), I'd use an inline if (x = a == null ? 0 : 1;) rather than if-else, but it's just my opinion.

like image 22
Fritz Avatar answered Oct 04 '22 17:10

Fritz