Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java one line if statement [duplicate]

Tags:

java

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?

like image 942
Subodh Joshi Avatar asked Nov 21 '13 09:11

Subodh Joshi


2 Answers

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
like image 191
user2314737 Avatar answered Sep 29 '22 12:09

user2314737


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

like image 28
benzonico Avatar answered Sep 29 '22 12:09

benzonico