Is It Ok If I Omit Curly Braces in Java

Is it ok if I omit curly braces in Java?

It won't change anything at all apart from the maintainability of your code. I've seen code like this:

for (int i = 0; i < size; i++)
a += b;
System.out.println("foo");

which means this:

for (int i = 0; i < size; i++)
a += b;
System.out.println("foo");

... but which should have been this:

for (int i = 0; i < size; i++) {
a += b;
System.out.println("foo");
}

Personally I always include the brackets to reduce the possibility of confusion when reading or modifying the code.

The coding conventions at every company I've worked for have required this - which is not to say that some other companies don't have different conventions...

And just in case you think it would never make a difference: I had to fix a bug once which was pretty much equivalent to the code above. It was remarkably hard to spot... (admittedly this was years ago, before I'd started unit testing, which would no doubt have made it easier to diagnose).

Is there a difference in removing the curly braces from If statements in java

For a single statement it will remain same, but if you want to group more than one statement in the if block then you have to use curly braces.

if("pie"== "pie"){
System.out.println("Hurrah!");
System.out.println("Hurrah!2");
}

if("pie"== "pie")
System.out.println("Hurrah!"); //without braces only this statement will fall under if
System.out.println("Hurrah!2"); //not this one

You should see: Blocks in Java

A block is a group of zero or more statements between balanced braces
and can be used anywhere a single statement is allowed. The following
example, BlockDemo, illustrates the use of blocks:

class BlockDemo {
public static void main(String[] args) {
boolean condition = true;
if (condition) { // begin block 1
System.out.println("Condition is true.");
} // end block one
else { // begin block 2
System.out.println("Condition is false.");
} // end block 2
}
}

(example from the above link)

Why is it considered a bad practice to omit curly braces?

Actually, the only time that's ever really bit me was when I was debugging, and commented out bar():

if(foo)
// bar();
doSomethingElse();

Other than that, I tend to use:

if(foo) bar();

Which takes care of the above case.

EDIT Thanks for clarifying the question, I agree, we should not write code to the lowest common denominator.

Why is it considered a bad practice to omit curly braces?

Actually, the only time that's ever really bit me was when I was debugging, and commented out bar():

if(foo)
// bar();
doSomethingElse();

Other than that, I tend to use:

if(foo) bar();

Which takes care of the above case.

EDIT Thanks for clarifying the question, I agree, we should not write code to the lowest common denominator.

Is it a bad practice to use an if-statement without curly braces?

The problem with the first version is that if you go back and add a second statement to the if or else clauses without remembering to add the curly braces, your code will break in unexpected and amusing ways.

Maintainability-wise, it's always smarter to use the second form.

EDIT: Ned points this out in the comments, but it's worth linking to here, too, I think. This is not just some ivory-tower hypothetical bullshit: https://www.imperialviolet.org/2014/02/22/applebug.html

Can I write a method body without curly braces {}?

Curly braces are required for methods.

From the Java Language Specification:

Method Body

A method body is either a block of code that implements the method or
simply a semicolon, indicating the lack of an implementation.

What is a block?

A block is a sequence of statements, local class declarations, and
local variable declaration statements within braces.

Also required for classes.

Class Body and Member Declarations

ClassBody:
{ {ClassBodyDeclaration} }

*Bold formatting is mine.

How to use If-Statement without add curly brackets?

In Java, braces ({}) are only required around conditional blocks that have multiple statements. Otherwise, only the first is executed conditionally. In essence:

if (something)
doThing1();
doThing2();
doThing3();

is really

if (something){
doThing1();
}
doThing2();
doThing3();

While it is true that they aren't required in these single statement conditional sections, it's considered extremely good practice to use them in any case: using braces where you didn't need them is harmless and future proof, but not using them where you need them has caused genuinely disastrous bugs in the past.

Is it considered correct to omit curly braces strictly on one-liners?

Is it considered correct to omit curly braces strictly on one-liners?

Well there isn't any hard rule on it. But considering the usability case, I'd always use a curly bracket. It makes the code more readable and for junior developer it's easy to understand. Again it's purely a personal/Company(code-standard) choice.

And again in your alternatives, I'd go for the Alternative2

public <E extends RuntimeException> void throwOnFail(final boolean result, final Supplier<E> exceptionSupplier) throws E {
Objects.requireNonNull(exceptionSupplier);
if (!result) {
throw exceptionSupplier.get();
}
}

Why?

  1. More concise
  2. Less number of lines
  3. Logically straight forward

Curly braces in if-else blocks

For example:

if (something)
if (something else)
...
else (blah blah)

Is the same that:

 if (something)
{
if (something else)
...
else (blah blah)
}

In this case, yes, they're the same, but the former is harder to read than the latter. I recommend using braces always, even for blocks of code made of a single line.

When are curly braces not required for multi-line loop bodies?

The trick here is the difference between a statement and a line. Loop bodies will only execute the next statement, unless there are curly braces, in which case the loop will execute the whole block inside the curly braces. (As mentioned in other answers, it is always good practice to use curly braces for every loop and if statement. This makes the code easier to understand, and easier to correctly modify.)

To your specific example:

An if-else statement in java is considered to be a single statement.

In addition, the following would be a valid single-line statement:

if(someBoolean)
someAction(1);
else if (someOtherBoolean)
someOtherAction(2);
else
yetAnotherAction();

You could add as many else-if's as you wanted, and the compiler would still view it as a single statement. However, if you don't use the else, it views it as a separate line. For example:

for(int a=0; a<list.size; a++)
if(list.get(a) == 1)
someAction();
if(list.get(a) == 2)
someOtherAction();

This code actually won't compile, because the second if statement is outside the scope of the for loop, hence the int a doesn't exist there.



Related Topics



Leave a reply



Submit