javacoding-stylecurly-braces

Which type of curly brace coding style is better for Java programmers?


I have seen in many tutorials, some programmers use curly braces in the same line with code. Others use curly braces on a separate line, and the rest uses mixed approach.

Should curly braces be on their own line or not?

if (you.hasAnswer()) {
    you.postAnswer();
} else {
    you.doSomething();
}

Or should it be the following?

if (you.hasAnswer())
{
    you.postAnswer();
}
else
{
    you.doSomething();
}

Or even the following?

if (you.hasAnswer()){
    you.postAnswer();
}
else{
    you.doSomething();
}

On the Oracle official site about code convention, they give code like this:

if (condition) {
    statements;
}

if (condition) {
    statements;
} else {
    statements;
}

if (condition) {
    statements;
} else if (condition) {
    statements;
} else {
    statements;
}

Solution

  • First or third. I favour the first for compactness mostly, but in "if else" trees sometimes use the third for 'syntactical simplicity' of commenting lines in/out.

    Vertical space is valuable, since research finds the comprehension limit of an algorithm is closely related to the vertical size that can be seen on one screen. Wasting vertical space with extra lines for unimportant if-branches is pointless.