I've searched for this, but couldn't find an answer and for whatever reason I was too ashamed to ask professor, due to that feeling when hundreds of people stare at you...
Anyhow, my question is what's the importance of having brackets? Is it OK if I omit them? Example:
for (int i = 0; i < size; i++) { a += b; }
vs
for (int i = 0; i < size; i++) a += b;
I know both of them will work, but if I omit the brackets (which I tend to do a lot, due to visibility) will that change anything, anything at all? As I said, I know it works, I tested it dozen of times, but now some of my uni assignments are getting larger, and for some reason I have irrational fear that in the long run, this my cause some problems? Is there a reason to fear that?
Java has a "feature" which allows you to omit curly brackets when writing if statements, for loops, or while loops containing only a single statement. You should never use this feature – always include curly brackets. The reason for this is because omitting curly brackets increases your chances of writing buggy code.
So we can omit curly braces only there is a single statement under if-else or loop. Here in both of the cases, the Line1 is in the if block but Line2 is not in the if block. So if the condition fails, or it satisfies the Line2 will be executed always.
If there is only one statement for the if condition, curly braces are optional but if there are a series of steps curly braces are mandatory. That being said, you always want to keep the option of adding more statements to an if condition later. It is more readable and reduces error or bugs.
Without curly braces only first statement consider in scope so statement after if condition will get executed even if there is no curly braces. But it is Highly Recommended to use curly braces. Because if the user (or someone else) ever expands the statement it will be required.
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).
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