Laying out Code
12 September 2007, late morning
C, and languages derived from it, use braces to indicate a block of code. The placement of braces is a very contentious issue. People can get quite passionate about their placement. I usually do the following:
int main(int argc, char* argv[])
{
bool found = false;
while ( !found )
{
if ( somefunc() )
{
...
}
...
}
...
}
You can line up any pair of braces to find the block of code they enclose. A lot of people don’t like this style, and prefer to line up the closing brace with the language construct whose block it is terminating.
int main(int argc, char* argv[]) {
bool found = false;
while ( !found ) {
if ( somefunc() ) {
...
}
...
}
...
}
I like the white space between control structure or function declaration and the code associated with it, so I usually don’t use this style. I find it a bit too cramped. Languages like Ruby naturally lend themselves to this style.
One style that some people recommend, but which I find incredibly ugly is the following:
int main(int argc, char* argv[])
{
bool found = false;
while ( !found )
{
if ( somefunc() )
{
...
}
...
}
...
}
I actually don’t know anyone who codes this way, but you do see this style come up again and again in books. It is so weird looking.
I’ll vote for the second block.
I’m also all about making lines run way past 80 characters. it drives me nuts when people are sticklers for that and it just makes for some unreadable multi-line method which breaks the flow of everything else.
by tyler rooney on September 12 2007, 1:59 pm #
I sometimes use the second style. It really depends what sort of mood i’m in when I start writing a new project. I almost always use the second style when writing CSS files.
I’ve started clipping longer lines and intending the continuation 2 tabs over. I try not to clip lines unless they are really long though, because it does make reading the code trickier.
by Ramanan on September 12 2007, 2:24 pm #
I use the first style. It is easier for me to read my methods that way. Stupid eclipse uses the second style though so when sifting through other peoples code I am always thrown off.
by Krishna on September 12 2007, 2:46 pm #
#2. Maybe I’ve just had to maintain too many 1000 line classes (in java) but I get annoyed when I have to scroll a lot. #1 adds unnecessarily to the vertical length.
by Jeff Egnaczyk on September 12 2007, 4:58 pm #
Style #2
Have you read Code Complete? It has a whole chapter about Layout and Style. (Style #1 is frowned up – the format of the structure is inconsistent with the logic of the structure; i.e. as there are two lines that begin at the left at the top).
by Ryan on September 12 2007, 10:44 pm #
I was actually thinking about this topic because I read that chapter in code complete. I borrowed that and the pragmatic programmer from my brother.
by ramanan on September 12 2007, 11:12 pm #