Question

this:

public void foo() {
    for (int i = 0; i < rows; i++)     // <--- no brace!
        for (j = 0; j < columns; j++)   // <--- no brace! 
            table[i][j] = new Blabla(i, j);
    other();
}

or this:

public void foo() {
    for (int i = 0; i < rows; i++) {
        for (j = 0; j < columns; j++) {
            table[i][j] = new Blabla(i ,j);
        }
    }
    other();
}
Was it helpful?

Solution

It's better to include the braces as otherwise someone might add an extra line thinking it will be inside the loop, but actually it will be run only once after the loop completes.

public void foo() {
    for (int i = 0; i < rows; i++)
        for(j = 0; j < columns; j++)
            table[i][j] = new Blabla(i, j);
            count++;                // <--- potential bug!
    other();
}

OTHER TIPS

The simple fact is, adding the brackets will induce fewer mistakes. I think once properly formatted the snippets are equally readable.

This is a matter of taste. Personally I always use brackets, because I like it and I has been bitten by the "add another statement which ends up outside the block because it wasn't delimited".

I've grown more lenient, because we now has as a policy to have Eclipse reformat all sourcefiles every time they are saved (called Save Actions), so the indentation is always right and doesn't trick you to think statements are inside a block when they are outside. Highly recommended.

I would always include the curlies unless it's only one statement in the body of the for (or any other statement like if/while) and you can see that it's a shortened style. If you leave the curlies out in your case, you could quite easily change the behaviour of the method by simply adding one method call at the wrong place, because you think it will land in the body of the for.

The second one is more readable.

I can deal with omitting braces from a single statement, but nesting that is too much.

Are you referring to the space before the bracket on the for loop?

I'd personally say no space there, but it doesn't keep me awake at night. The most important thing is to be consistent.

for very simple an clear code like that, no brace.

if someone comes and adds something in the wrong scope, paying no attention to the surrouding code, giving no second look at the new code, I wouldn't have him touch my code ever again.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top