PDA

View Full Version : Indentation practice



sriram139
5 Feb 2013, 8:34 AM
There are multiple ways one can indent their code, two of them that are commonly used styles are as below:

1) Start the block on same line with open brace following the last character of that block header:

if(...){
<block code>
}

2) Start the block in new line with open brace in the next line:

if(...)
{
<block code>
}

Both these approaches have their own pros and cons.
However, I want to know which does Sencha team prefers the application developers to follow and reason behind using particular style of indentation. Specifically, I want to know if there are any disadvantages in following the second style of indentation as I feel it helps in improving the readability of code than the former.

Thanks,
Sriram

mitchellsimoens
7 Feb 2013, 8:09 AM
This is really a matter of developer style. I personally keep it in one line:


if (...) {
....
}

And most do that as well. I do see a difference in the else so I see this:


if (...) {
...
} else if (...) {
...
} else {
...
}

but also see:


if (...) {
...
}
else if (...) {
...
}
else {
...
}

The 2nd bit I can see useful if you need to add some comments but it just looks weird to me but that's just my code style.

Dipish
7 Feb 2013, 8:21 AM
Actually, it's a little more than just a matter of style.

The "same line braces" way is preferred in JavaScript in order to avoid some quirks with Automatic Semicolon Insertion (ASI).

The classic example is the following:

function foo() {
return
{
bar: "foobar"
};
}


in most js implementations will be equivalent to


function foo() {
return;
{
bar: "foobar"
};
}


and of course will return undefined. Of course not all situations involving curly braces are dangerous like this but for the sake of consistency, always put a brace on the same line. As an added bonus, "same-line braces" is a little more compact :)

More reading:
http://stackoverflow.com/questions/3218756/javascript-braces-on-new-line-or-not
http://stackoverflow.com/questions/3960518/javascript-formatting-must-braces-be-on-the-same-line-as-the-if-function-etc-ke


(http://stackoverflow.com/questions/3218756/javascript-braces-on-new-line-or-not)