This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
The reason for always having braces is to make absolutely clear what is included in the conditional statement. Put simply, if you always use braces, then you always have one style. If you don't, then you are using two styles: one for conditionals containing one statement, and one for multi-line ones. In my opinion, code clarity always overrules brevity.
Joined: Aug 19, 2003
My question can be best understood this way
does during the compilation of the java file into .class files , the compiler has to explicitly insert the braces for a non braced if?...i know its not an over head if so, however we would like to keep the compiler happy
Joined: Feb 23, 2005
Don't get things the wrong way round
The compiler understands both formats, so it doesn't need to put the braces in so it can then understand them!
Don't worry about the compiler - worry about the clarity of your code.
When modifying code without the braces, this is a very common error:
Actually you're fairly lucky here because the else will likely be unbalanced. But can you see how this appears to do one thing but compiles to do something else?
Now to be honest, I leave the braces out fairly often. I use the code formatter in Eclipse after every couple lines of typing so I'm not usually fooled by false indentation like that. Still, it's a pain to go back and insert braces later, and I do encourage you to get in the "always use them" habit, even if I didn't.
A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
If you're using Eclipse (or any other modern editor), turn on templates. That way, you type "if" and hit the spacebar, and the editor puts inwhere ^ is the new position of the caret for typing text and ... is just there to show you it's indented. I haven't typed a brace in Java in years. Well, okay, I have when fixing other people's code.
There is one place where I don't use braces: debugging. I have methods defined in my classes to help do Log4j logging.When you're learning something new, it's best to stick to one method of doing it. Once you gain experience, you'll become comfortable with altering your style as you see fit. If you try to do that early in your training, you'll hamper your progress. [ March 07, 2005: Message edited by: David Harkness ]