Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android standard brace style legality

Reading this piece of information, it states that:

We require braces around the statements for a conditional. Except, if the entire conditional (the condition and the body) fit on one line, you may (but are not obligated to) put it all on one line. That is, this is legal:

if (condition) {
    body(); 
}

and this is legal:

if (condition) body();

but this is still illegal:

if (condition)
    body();  // bad!

Why is the last mentioned bad? It is a mix of the two above, but what is the motivation for not using that kind of style? IMO, it is the most readable (or equaly readable to the first one).

I know that may not apply to Android specifically, but it's the first place I've heard about it.

like image 616
whirlwin Avatar asked Jun 24 '11 13:06

whirlwin


1 Answers

In the code you have that is bad style, you have a problem with languages that don't use indentation to determine what to do with the code. Imagine I'm maintaining your code and see this:

if (condition)
    body();  // bad!

I decide to add a line to it, to make it this:

if (condition)
    body();  // bad!
    myconditionalfcn(); // Will always execute

The other two styles you have prevent this mistake, one by making the entire conditional a single line, and the other by ensuring I enter my new function inside the braces.

When working on someone else's project, you should never break their style. When working on your own project, you should strive for readability in your style--the problem with the second, in terms of readability, is that it can cause confusion like the above. A good editor will let you auto-correct this error, but it's (almost) always better to avoid it in the first place by not having single line conditionals split like that.

like image 142
Dylnuge Avatar answered Sep 28 '22 02:09

Dylnuge