Coding Style: Curly Braces

Started by
72 comments, last by kunos 11 years ago

I use K&R style.

With one exception:

This is super ugly:


if (foo) {
    bar();
} else {
    baz();
}

Wile this is great:


if (foo) {
    bar();
}
else {
    baz();
}

I think it's called CCR style. Compact control readability.

Advertisement

I use K&R style.
With one exception:

This is super ugly:


if (foo) {
    bar();
} else {
    baz();
}
Wile this is great:

if (foo) {
    bar();
}
else {
    baz();
}
I think it's called CCR style. Compact control readability.


honestly, for something like that, I think both are ugly, and would prefer the compact:

if(foo) bar();
else    bar();
Check out https://www.facebook.com/LiquidGames for some great games made by me on the Playstation Mobile market.

I use the latter one, ...however the first one is more readable for everyone in general. IMO

Plus I add a few conventions. Like if I put a linebreak when there is more than 1 statement after the cycle-s or if-s.

for( something){

while( something){

if( something){

statemet1;

statemet2;

statemet3;

}

}

}

...makes it more readable.

I always look at control blocks with one line, no braces and think "Someday I'm going to mess this up" So I always put braces even if the if/else block can fit in a single line.

Something I took from Id Software coding style manual is the spacing between parenthesis, ie:

if ( this.vertexBuffer == null )

if ( enable )

if ( this.dirty )

And so on. Its more pleasing to the (my) eye.

Sometimes, if the conditions are many I treat the parenthesis as if it were another curly braces block like this:



mode = modeArray;
if
( 
    mode.getWidth() == width &&
    mode.getHeight() == height &&
    mode.getFrequency() == 60 &&
    mode.getBitsPerPixel() == 32
)
{
    Display.setDisplayMode(mode);
    break;
}
This one I haven't seen it elsewhere yet.

"I AM ZE EMPRAH OPENGL 3.3 THE CORE, I DEMAND FROM THEE ZE SHADERZ AND MATRIXEZ"

My journals: dustArtemis ECS framework and Making a Terrain Generator

I'll do that occasionally. More often, though, I'll just put the condition into a bool and then run the bool through the if statement.


mode = modeArray;

bool resetDisp = 
  (mode.getWidth() == width) &&
  (mode.getHeight() == height) &&
  (mode.getFrequency() == 60) &&
  (mode.getBitsPerPixel() == 32);

if(resetDisp) {
    Display.setDisplayMode(mode);
    break;
}
void hurrrrrrrr() {__asm sub [ebp+4],5;}

There are ten kinds of people in this world: those who understand binary and those who don't.

bool f1() {
	//...
}

bool f2() {
	//...
}

bool f3() {
	//...
}

if(f1()) {
	if(f2()) {
		if(f3()) {
			//...
		}
	}
}

To me, this is the clearest way. Why waste a line, when it's clear that if you have proper indentation, the close bracket will always align with the statement that opens it?

(we all want to read code that looks exactly like our style I'm sure).

Well, my approach is something like this:

1 - practice reading code in a lot of different styles and get comfortable with doing it

2 - practice *writing* code in a lot of different sales and get comfortable with doing it

3 - get to know and use the formatting tools of your IDE

4 - be consistent and follow style of the code that you are working with

Consistency is far more important that the particular style.

What style do you tend to use and like better? What are you reasons you chose that specific style for curly braces?

The primary formatting tool is whitespace, and I personally prefer lots of whitespace and large monitors to compact code so curlys usually get the line to themselves.

openwar - the real-time tactical war-game platform


f(f1()) {
	if(f2()) {
		if(f3()) {
			//...
		}
	}
}

To me, this is the clearest way. Why waste a line, when it's clear that if you have proper indentation, the close bracket will always align with the statement that opens it?

The reason this style is bad is because it's inconsistent and doesnt align the matching braces. The opening brace is at the end of the first line of the code block, while the closing grace is inexplicably on its own line after the code block. No consistency whatsoever. Since you're aligning the end-brace with code instead of an open-brace, that open brace might not even be there and you'd never notice until the compile fails, which might be a significant amount of time wasted on big projects.

It's not even consistent with what you claim to be the reason for using it... namely because you dont want to "waste a line". I'm not sure why you think that packing your code together as much as possible is desirable (it's not), but if that's the case then why put the closing brace on a separate line? Why is "wasting" that line acceptable? By your logic, this is the code you should be writing:


if(f1()) {
	if(f2()) {
		if(f3()) {
			/*...*/ } } }

No "wasted" lines there, and the brace placement is consistent... always at the end of the first/last line. And, of course if you really dont want to waste lines, then this is what you should be doing:


if(f1()) { if(f2()) { if(f3()) { /*...*/ } } }

There you go, I just saved you 86% of the lines in that code block and made the brace placement perfectly consistent. You dont have to thank me.

Now, for those of us that dont want to pack code into an indecipherable brick, having braces on their own lines gives a natural break to separate sections of code for better readability, and has the advantage that braces are always aligned with each other, making the pattern easy to spot from a mile away. For example:


void Character::SaveState(FILE *pFile){
	fwrite(&mHealth, 1, sizeof(mHealth), pFile);
	fwrite(&mMoney, 1, sizeof(mMoney), pFile);
	fwrite(&mPosition, 1, sizeof(mPosition), pFile);
	fwrite(&mWeapon, 1, sizeof(mWeapon), pFile);
}

as opposed to:

void Character::SaveState(FILE *pFile)
{
	fwrite(&mHealth, 1, sizeof(mHealth), pFile);
	fwrite(&mMoney, 1, sizeof(mMoney), pFile);
	fwrite(&mPosition, 1, sizeof(mPosition), pFile);
	fwrite(&mWeapon, 1, sizeof(mWeapon), pFile);
}

A cursory look through the second set of code easily distinguishes the function declaration from the code in the body, making both easier to read. Even better would be:


void Character::SaveState(FILE *pFile)
{
	fwrite(&mHealth,   1, sizeof(mHealth),	 pFile);
	fwrite(&mMoney,	   1, sizeof(mMoney),	 pFile);
	fwrite(&mPosition, 1, sizeof(mPosition), pFile);
	fwrite(&mWeapon,   1, sizeof(mWeapon),	 pFile);
}

Here your brain can use its full pattern-matching abilities to easily spot discrepancies as quickly as possible. Finding bugs in code like this becomes extremely easy because you're not fighting your brain and intentionally obfuscating the code, you're actually using the code formatting to help in finding errors.

-snip-

The reason this style is bad is because it's inconsistent and doesnt align the matching braces. The opening brace is at the end of the first line of the code block, while the closing grace is inexplicably on its own line after the code block. No consistency whatsoever. Since you're aligning the end-brace with code instead of an open-brace, that open brace might not even be there and you'd never notice until the compile fails, which might be a significant amount of time wasted on big projects.

It's not bad. It's just not the style you use. The end brace matches the block owning statement. It reads very naturally to people who prefer that style.

void hurrrrrrrr() {__asm sub [ebp+4],5;}

There are ten kinds of people in this world: those who understand binary and those who don't.


f(f1()) {
	if(f2()) {
		if(f3()) {
			//...
		}
	}
}

To me, this is the clearest way. Why waste a line, when it's clear that if you have proper indentation, the close bracket will always align with the statement that opens it?

The reason this style is bad is because it's inconsistent […] The opening brace is at the end of the first line of the code block, while the closing grace is inexplicably on its own line after the code block. No consistency whatsoever.

Consistency has to do with picking one style and sticking to it throughout the code base. It has nothing to do with braces being on the same indentation level.

The reason this style is bad is because [it] doesnt align the matching braces.

How is that bad? People tend to scan 90% by indentation levels, and since bad indentation will screw up anyone in either style it is always necessary for indentation to be consistent.
So, when combined with the following quote of yours:

Now, for those of us that dont want to pack code into an indecipherable brick, having braces on their own lines gives a natural break to separate sections of code for better readability, and has the advantage that braces are always aligned with each other, making the pattern easy to spot from a mile away.

…the other side could question why you get so tripped up over such a small detail. Training yourself to spot specifically the opening brace rather than just anything on the same indentation level seems counter-intuitive and self-limiting. After all, you wouldn’t spot the opening brace unless it was on the same indentation level as the closing brace, so you wouldn’t spot that any faster than the other side would spot the if, else, while, for, etc. In fact it takes you more effort and time since you are apparently looking for one specific character, when the other side is looking for anything on the same indentation level. Once the other side finds anything on the same indentation level, they immediately say, “Ah, found it,” whereas you say, “Ah, okay is it an opening brace? Okay found it.”

The other side might then say that if you claim to spot things just as quickly as they do, then you aren’t truly looking for specifically an opening brace; you are going entirely by indentation level, since it is matter-of-fact that checking for specific characters is an extra step that can’t be done in the same amount of time by the same processor.
So then the other side would question why the brace needs to use an extra line on its own if it is not actually helping you align things with closing braces. Then it becomes quite obvious that you can’t actually say it has any justifiable purpose, but rather just that you prefer it to be on the same level as the closing brace, as a matter of your own personal taste and nothing more.

This gives the other side a legitimate claim to it being a waste of space. By their logic, it serves nothing more than to placate your personal taste, but with the downside of moving a few lines of code off the bottom of the screen. That doesn’t mean they want the code as compact as possible, but that they prefer to choose where to compact it or where to not.

For example:


	LSUINT32 LSE_CALL CTime::GetConstantStepUpdateTimesFromTicks( LSUINT64 _ui64Ticks, LSUINT32 &_ui32UnitsToNextUpdate ) {
		LSUINT64 ui64TimeNow = GetRealTime();
		LSUINT64 ui64Dif = ui64TimeNow - m_ui64LastRealTime;

		LSUINT32 ui32Count = static_cast<LSUINT32>(ui64Dif / _ui64Ticks);
		m_ui64LastRealTime += ui32Count * _ui64Ticks;

		// Determine how far this update lands between two other updates at the same fixed interval,
		//	in units of 1 1,000th.
		_ui32UnitsToNextUpdate = static_cast<LSUINT32>(((ui64Dif % _ui64Ticks) * 1000ULL) / _ui64Ticks);

		return ui32Count;
	}

Blank lines were added to make logical separations between segments of code, and a 2-line comment added for clarity on the return.
The other side won’t see a purpose in adding an extra line after the function declaration just for the brace because it doesn’t improve readability in any way—blank lines were added in strategic places rather than religiously at the start of the function, and it is very clear where the function body begins based on indentation levels alone.

I am offended that you use a style other than my own so let me twist your logic and write a totally out-of-context example:


if(f1()) {
	if(f2()) {
		if(f3()) {
			/*...*/ } } }

Let me try to offend you even more by throwing all logic out the window and pretend the concept of indentation levels just doesn’t exist, even though I use them myself when scanning for matching braces:

if(f1()) { if(f2()) { if(f3()) { /*...*/ } } }

Careful, someone might misunderstand that you are close-minded and stuck in your own ways, justifying them as “the best” based solely on the fact that it is what you prefer.

Of course, we all know better than that, right? wink.png

L. Spiro

I restore Nintendo 64 video-game OST’s into HD! https://www.youtube.com/channel/UCCtX_wedtZ5BoyQBXEhnVZw/playlists?view=1&sort=lad&flow=grid

This topic is closed to new replies.

Advertisement