11

I am using if condition without braces in java something like

if(somecondition)
//Only one line Business logic

but some told use braces always even one line statement something like this

if(somecondition){
//Only one line Business logic 
}

What is the better way according to java sandard?

Subodh Joshi
  • 12,717
  • 29
  • 108
  • 202

8 Answers8

18

there's no real "standard". i prefer always using braces because if you dont you risk someone adding an innocent looking logging statement turning your code from

if(somecondition)
//Only one line Business logic

into

if(somecondition)
log.debug("condition was true");
//Only one line Business logic

and then things stop working :-)

radai
  • 23,949
  • 10
  • 71
  • 115
16

That's a matter of taste. I would use braces or else no braces but write all code in one line to improve readability.

Also you might consider using a ternary operator

booleanExpression ? value1 : value2
user2314737
  • 27,088
  • 20
  • 102
  • 114
8

In addition to @radai answer, if you are a real evil mind, when you see a if with no braces you can do something that will make you ennemies by adding a semi-colon on the same line of the if but at the 800th column of the line(or something).

like

if(condition) /*a loooot of whitespace*/ ;
    //Only one line Business logic that will get executed whatever is the condition

This is why i prefer to use braces and recommend people to use them

benzonico
  • 10,635
  • 5
  • 42
  • 50
5

No naked if statements. You're just asking for trouble. Always use { }

Shaun
  • 3,777
  • 4
  • 25
  • 46
2

it is better to use braces when checking for errors or updating the code.

imagine.

if(answer.equals("add"))
    addedValue += Scanner.readInt();

but you have a new requirement to add only the absolute value, so you change to.

if(answer.equals("add2))
    valueToBeAdded = Scanner.readInt();
    if(valueToBeAdded < 0) valueToBeAdded = - valueToBeAdded;
    addedValue += valueToBeAdded;

this is not a really correct algorithm, is just an example of what can happens.

RamonBoza
  • 8,898
  • 6
  • 36
  • 48
1

Using if statement with braces is better way to java standard, because it increase the readability and reduce unwanted error.

Masudul
  • 21,823
  • 5
  • 43
  • 58
1

The two statements have exactly the same effect but I have suffered so often from the lack of braces that I also always comment that there should be braces even around 1 line statements. This makes the code easier to maintain and can save a lot of headache. My experience shows that one line if statements often turn into multi-line statements on later iterations so what you save by not writing two { the first time, you will give later on.

Ivaylo Strandjev
  • 69,226
  • 18
  • 123
  • 176
0

According to java standard braces are better because if they are not there compiler has to work around more and also would be performance issue.

shreyansh jogi
  • 2,082
  • 12
  • 20