Allman style v. K&R style/one true brace style

Talk about anything
User avatar
jeeswg
Posts: 6902
Joined: 19 Dec 2016, 01:58
Location: UK

Allman style v. K&R style/one true brace style

10 May 2018, 13:53

- Usually in programming, there are advantages and disadvantages to different approaches. I am not usually concerned with other people's individual style choices, only that they have a consistent style.
- However, I'm finding more and more that in the indentation style debate, an unfortunate style is quite prevalent (K&R style/one true brace style), whereas I don't see the IMO much better Allman style as much as I would like.
- Would anyone be willing to try to defend the K&R/1TBS style?

- Here's an example I saw recently. I find the 'after' version much easier to take in and understand, and for larger and more complicated scripts, in particular scripts where object classes are defined, the advantage of using Allman style is even greater.

Code: Select all

;Help with Count++ in my script - AutoHotkey Community
;https://autohotkey.com/boards/viewtopic.php?f=5&t=48732&p=217296#p217296

;==================================================

;BEFORE

F10::
loop {
    send x
    if(!mod(a_index,10)){
        send a
        sleep 1000
    }
    sleep 50
}
return

;==================================================

;AFTER

F10::
loop
{
    send x
    if(!mod(a_index,10))
    {
        send a
        sleep 1000
    }
    sleep 50
}
return

;==================================================
- A useful link:
Indentation style - Wikipedia
https://en.wikipedia.org/wiki/Indentation_style

- Btw I'm not saying anything re. 'braces are not omitted for a control statement with only a single statement in its scope'. I feel pretty neutral on the subject. At the moment I always omit braces for one-liners.

Code: Select all

;STYLE: always omit braces for one-liners:
if (var = 1)
	MsgBox(1)

;STYLE: always use braces for one-liners:
if (var = 1)
{
	MsgBox(1)
}

;STYLE: use braces for one-liners if another if/else branch is a two-or-more-liner
if (var = 1)
{
	MsgBox(1)
}
else
{
	MsgBox(2)
	MsgBox(2)
}
- For styles more generally.

Code: Select all

;STYLE: Allman style
if (var = 1)
{
	MsgBox(1)
	MsgBox(1)
}
else if (var = 2)
{
	MsgBox(2)
	MsgBox(2)
}
else
{
	MsgBox(3)
	MsgBox(3)
}

;STYLE: Horstmann style (adapts Allman by placing the first statement of a block on the same line as the opening brace)
if (var = 1)
{	MsgBox(1)
	MsgBox(1)
}
else if (var = 2)
{	MsgBox(2)
	MsgBox(2)
}
else
{	MsgBox(3)
	MsgBox(3)
}

;STYLE: K&R: Stroustrup (no 'cuddled else')
if (var = 1) {
	MsgBox(1)
	MsgBox(1)
}
else if (var = 2) {
	MsgBox(2)
	MsgBox(2)
}
else {
	MsgBox(3)
	MsgBox(3)
}

;STYLE: K&R: 1TBS/OTBS (one true brace style)
if (var = 1) {
	MsgBox(1)
	MsgBox(1)
} else if (var = 2) {
	MsgBox(2)
	MsgBox(2)
} else {
	MsgBox(3)
	MsgBox(3)
}
homepage | tutorials | wish list | fun threads | donate
WARNING: copy your posts/messages before hitting Submit as you may lose them due to CAPTCHA
User avatar
Nextron
Posts: 1386
Joined: 01 Oct 2013, 08:23
Location: Netherlands OS: Win10 AHK: Unicode x32

Re: Allman style v. K&R style/one true brace style

10 May 2018, 16:15

I think your Wikipedia link makes a good point:
Programmers who rely on counting the opening braces may have difficulty with indentation styles such as K&R, where the starting brace is not visually separated from its control statement. Programmers who rely more on indentations will gain more from styles that are vertically compact, such as K&R, because the blocks are shorter.
If you don't indent or do it wrong, either style will be hard to read, although Allman will probably suffer less. I see indenting as the actual way to make code readable and braces just as an annoying requirement of the language, which I don't want to spend another dedicated line on by putting a opening brace on its own line, thereby stretching out the code.

I think Python manages this in an awesome way by making indentation levels functional by grouping lines into blocks. If that would be possible in AHK I would use it in a second.
User avatar
Flipeador
Posts: 1205
Joined: 15 Nov 2014, 21:31
GitHub: Flipeador
Location: Argentina
Contact:

Re: Allman style v. K&R style/one true brace style

10 May 2018, 19:24

I think Python manages this in an awesome way by making indentation levels functional by grouping lines into blocks. If that would be possible in AHK I would use it in a second.
+999 ;)
Windws 1♂ Pro 64-Bits I make scripts for AHKv2 & WIN_7+ Argentina
User avatar
jeeswg
Posts: 6902
Joined: 19 Dec 2016, 01:58
Location: UK

Re: Allman style v. K&R style/one true brace style

19 May 2018, 22:13

The 1 true style - xkcd
http://forums.xkcd.com/viewtopic.php?t=15060

Code: Select all

if(condition) {
   statement();

to me looks too similar to this:

if(condition)
    statement();
java - Only want to ever see Allman style code and save K&R style code - Stack Overflow
https://stackoverflow.com/questions/687 ... style-code
From my own anecdotal research, the main advantage to K&R most often cited, other than homage to earlier precedent, is that K&R is a style favored by those that like to see more code on one screen. Yes, it is true, that's the main reason. Code density. I thought this issue would have died its final death once we got past the age of 80 x 25 character console screens in the early 90's, but alas, but it seems not to have mattered. So for those that like code density so they can see more code on one screen at a time, we suffer with millions of lines of K&R style code. * Sigh *
The Only Correct Indent Style | Terminally Incoherent
http://www.terminally-incoherent.com/bl ... ent-style/

I created a table of the results:

Code: Select all

6300	37.4%	K&R
8950	53.2%	Allman
520	3.1%	Whitesmith
527	3.1%	GNU
150	0.8%	Horstman
109	0.6%	Pico
278	1.7%	Banner

16834	Total Votes

Started: April 6, 2009
The Only Correct Indent Style | Terminally Incoherent
http://www.terminally-incoherent.com/bl ... ent-style/
==================================================

Allman is the ONLY indent style you should be using. Visual Studio (best IDE out there) has it as a default, as does ANSI standard. The only reason K&R used to be popular, is because back in the 80’s all programmers had were crappy 24 line monitors, so you had to preserve space. If you can’t afford a decent 20″ or bigger monitor these days, you’ve got bigger problems than indentation… A serious programmer needs at least 2 or three monitors anyway…

K&R is for amateurs – listen to professionals and stick to Allman’s.

==================================================

Allman. K&R is a travesty. People trying to save that one extra line at the expense of clarity should be shot.

You like saving space so much, why don’t you go a step further and just write the entire block on one line.

if(x==y){x++;foo();}else{x–;bar();}

As for those other styles WTF, are they TRYING to be ridiculous?

@ tino “This is how the people that invented the language wrote the code, and if you are using their syntax, why do you second-guess their indentation? They knew what they were doing.”

You do know they had tiny green monitors, right? They tried to conserve a bit of space, and I don’t blame them, but today’s programmers have no excuse.

==================================================

Allman. The opening brace should be below its statement. The extra line and the fact that the braces line up vertically makes it easier to tell the structure of the code. Also I insist that the braces must be at the same indentation level as the associated control statement or function declaration, so those other weird styles are definitely out. I once worked with a guy who liked Horstmann, and found it to be acceptable to me. K&R tends to drive me nuts; its compactness inevitably makes code harder to read – I consider conciseness to be primarily a trait of the code itself, not the indent style around it.

==================================================

K&R tends to drive me nuts; its compactness inevitably makes code harder to read – I consider conciseness to be primarily a trait of the code itself, not the indent style around it.

==================================================

For some this might look something small. I believe it is something that has to do with logic and how do we perceive things. In all my works I had to do use the ugly old fashioned K&R style , but when I could I used Allman style and although that weren’t the policy, every one else could read my code easier so they didn’t complained. I am very happy to see that Allman style is gaining, and maybe in few years will be the programming industry main coding style.

==================================================

I prefer Allmann. Blocks are easier to identify viusally by level of indentation.

==================================================

It’s Allman dude! I’m really really frustrated when reading K&R. It makes my eyes squint :(

==================================================

when I started learning C Allman always made most sense to me – without knowing that it was “Allman”. For me it feels most intuitive and natural. Most will argue that K&R is the original and that Allman is a waste of space but I think that’s a low price for maintainability. I’m surprised that it got most of the votes now because “out there” (work and especially in the open source area) you mostly see K&R or Stroustrup style. I never could convince people to use Allman. So I had to to compromise and also got used coding in other styles. Jeet Kune Do or Bruce Lee style if you will. :P
In the end I don’t think you can really argue about it because it all comes down to personal preference.

==================================================

ALLMAN style is by far the best… and I wish it was made the defacto standard for languages like Java, C++, and C# because I’m tired of being told to do it the K&R way.

The reason some of the other styles were invented was to save space on screen by reducing the number of lines of code. This allowed book publishers to save some paper at the cost of reduced readability.

Bottom line: Allman style is the easiest to read and the most “foolproof”. You are less likely to forget an opening brace using Allman style, and it’s easier to work with blocks of code. Start spreading the word and get people to switch back to this style! (It is standard at Microsoft by the way.)

==================================================

Fair enough. Whether it’s page space in textbooks or screen space on tiny low resolution displays from the 1970’s, the K&R style of formatting tries to solve a problem that is no longer a problem at the expense of making code more difficult to read. The notion of “saving lines of code” is outdated.

When looking at other coding styles besides Allman, they all have serious drawbacks:

– K&R looks awful (the code looks broken), wrecks the block structure of the code, and makes it easy to forget opening braces by making them difficult and unpredictable to locate. (Since every line is a different length.)

– GNU requires too many tabs and too much maintenance regarding the indenting. It also wrecks the block structure of the code by creating an imaginary additional indent “level” that does nothing.

– Horstman is horrendous because you can’t easily copy/paste code lines around without blowing away the braces.

– Pico and Banner are a “dog’s breakfast” to try and read. Compact yes, but horrific to look at and likely the cause of most of the world’s programming bugs.

– Whitesmith is an inaccurate/failed version of Allman because the braces that delineate the start and end of the block are not where the actual start and end of the block is. The braces are simply at the wrong level.

The only drawback to using Allman style is that the code is spread over more lines, a problem long since resolved with larger, higher resolution monitors, and the use of classes to break code into smaller more manageable chunks.

==================================================

I guess I would strongly question how that code base was designed and why it has functions with over a thousand lines of code in them. As you suggested, it sounds like there’s more wrong there than any particular indenting style alone can fix.

Another point I wanted to mention was ROW LENGTH. Some of the most unreadable code that I’ve ever seen is unreadable because of artificially restrictive row lengths on the code lines. Instead of having one easy to read line, it gets split into two or even three lines of code. While it may be true that humans prefer narrow columns when reading novels, programmers prefer to maintain the block and command structure in their code. If a command statement such as a compound IF can be kept to one line instead of two, it becomes more readable. If a function call displays all arguments passed in on the same line, it’s easier to read than having them waterfall underneath.

I guess the three areas of programming I would change (if I could) is the following:

1. Allman style indenting would be the standard for all languages that use braces.

2. Row lengths would be increased to take advantage of wide screen monitors and reduce unnecessary line continuations in code.

3. I would beat programmers over the head with a stick for not putting comments in their code. (Arguably my greatest pet peeve.)

To date, there has never been a software project that had too much documentation. 99.9% of software projects don’t have enough or don’t have any. Having been put into the “wonderful” position of having to maintain other programmer’s junk on several occasions, I’m the guy that companies hire to tell them how their system actually works (since nobody understands it) and to document it so that future developers have an easy job. I can literally pick up a piece of my code from 10 years ago, look at a few of my comments, know exactly what I need to do, and pick up where I left off without missing a beat. But I digress…

==================================================

Another point I wanted to mention was ROW LENGTH. Some of the most unreadable code that I’ve ever seen is unreadable because of artificially restrictive row lengths on the code lines.

==================================================

When I first learned C, the professor used the K&R style, but when I wrote my code, it looked like the Allman style. It just seemed more organized to me. It was easier for me to keep track of the braces. My professor would comment about how easy it was to read my code (I assumed it was because I coded so well–maybe it was just the coding style).
I use the same style whether I’m in C, C++, C#, or Java.

==================================================

My professor would comment about how easy it was to read my code (I assumed it was because I coded so well–maybe it was just the coding style).

==================================================

@James:

I agree. I was taught to use the Allman style in school, and it was the default “template” in Visual Studio for writing code when I was in school. Whenever an editor tries to enforce a K&R style, I change the template right away.

I’ve noticed that the K&R community has been trying very hard to foist their style on everyone, and I truly believe that over the long run it will lose out to the Allman style.

A standard is determined by what the majority of people want to use, not what a small group of eggheads in ivory towers think the world should use. That’s why it isn’t surprising that Allman style is the preferred style. Allman style is what people want to use because it’s more natural, easier to read, and less prone to bugs. Those factors make it the clear winner on indenting style and brace location.

==================================================

A standard is determined by what the majority of people want to use, not what a small group of eggheads in ivory towers think the world should use. That’s why it isn’t surprising that Allman style is the preferred style. Allman style is what people want to use because it’s more natural, easier to read, and less prone to bugs. Those factors make it the clear winner on indenting style and brace location.

==================================================

Holy sht K&R is disgusting. Allman is clearly the choice of the mentally superior crowd. There’s simply no logical benefit to placing a brace on the end of the line instead of at the beginning of the next, if you’re going to have a blank line after the K&R version anyway… which you should, because this is just fcking hideous:

Code: Select all

 void thisCoderHasBadStyle() {
   string noBlankLinez4Me;
   if (noBlankLinez4Me == "ugly") {
     cout <<"damn this is some gross code.";
     cout <<"just a cluster of sht.";
   }
 }
==================================================

It’s like religion. No matter how much evidence is shown that the K&R believers believe in things that do not exist, it is ignored. You can check in Allman code into the repository till the cows come home. Even when it clearly looks much neater and easier to scan, they will simply not see it.
I absolutely can not stand K&R. It’s horribly cryptic. Try reading code with long lines. It’s really awful.

==================================================

Allman hands down.

Code should be clean and easy to read, If code would only be relevant to a single person then all this shitty messy styles would be okay, but that’s far from the truth.

I hate working with people that write code as fast as they can, without thinking who might read their hieroglyphs other than themselves,

An example a successfull Allman’s style C++ beast, is Unreal4, they have a very strict convention that makes contributing to the source a pleasure.

==================================================

An example a successfull Allman’s style C++ beast, is Unreal4, they have a very strict convention that makes contributing to the source a pleasure.

==================================================

I started with K&R and said Allman is ugly. Then I tried Allman and now K&R is ugly for me. Use a style for a while and it becomes your style.
K&R is nice compact, but Allman is better to read. If you read your code after 1 year, readability is important, not a compactness.

==================================================

K&R is nice compact, but Allman is better to read. If you read your code after 1 year, readability is important, not a compactness.

==================================================

@ Tino:
“They knew what they were doing”.

Yeah, and they probably had to work with tiny green phosphor CRT screens where you couldn’t afford to waste any screen real estate. But this is 2016, and we all get to work with big LCD displays with millions of pixels, so the “more compact” argument doesn’t hold water.

And I don’t buy the habit argument either. Having braces aligned vertically *does* make it faster to quickly spot blocks, and plays nice with folding editors.

Allman FTW.

==================================================
homepage | tutorials | wish list | fun threads | donate
WARNING: copy your posts/messages before hitting Submit as you may lose them due to CAPTCHA
User avatar
Chunjee
Posts: 1238
Joined: 18 Apr 2014, 19:05
GitHub: Chunjee

Re: Allman style v. K&R style/one true brace style

14 Sep 2019, 23:29

I started with Allman and would recommend it for most AHK scripts as some flows demand it.

Changed to K&R/1TBS because if you look at any code examples online that is what you'll likely see and I must have just started "speaking" it after a while. While Allman is probably more explicitly clear, I think K&R is kindof medium density understandable and doesn't dedicate entire lines to open brackets.

Probably won't be switching back but this post and links have certainly made me pause and think.

I would be very interested in a plugin or script for style enforcement as I'm probably a little all over the place with older libraries.
Another point of interest: https://github.com/airbnb/javascript
Last edited by Chunjee on 16 Mar 2021, 13:29, edited 2 times in total.
User avatar
jeeswg
Posts: 6902
Joined: 19 Dec 2016, 01:58
Location: UK

Re: Allman style v. K&R style/one true brace style

15 Sep 2019, 10:36

- Curiously, K&R uses Allman style for function definitions.
- K&R: Stroustrup (see above) is an interesting variant of K&R, with slightly better readability.
- K&R is OK for short if-clauses and no nested indentation. But for me it's simpler to always use Allman style. (K&R is OK for simple situations, i.e. when the stakes are low.)

- Horstmann style (see above) has the line-saving benefits of K&R. I think it's just tradition that Horstmann isn't more widely used. It's certainly better than K&R. Perhaps K&R is only widely used because of the K&R book. (I would be prepared to refuse to use K&R, despite its prevalence, but I might concede to using Horstmann style if it was widely prevalent, even if I preferred Allman style.)

- The poll suggests that Allman style is winning the Indentation Wars. And it's just going to take a key book/document ('the new C++ manual'/'K&R considered harmful'/more views for that webpage's poll) to consolidate Allman style/Horstmann style as the default.
- Another factor would be if editors would slightly shrink any lines that solely contained braces, to save vertical space.
homepage | tutorials | wish list | fun threads | donate
WARNING: copy your posts/messages before hitting Submit as you may lose them due to CAPTCHA
SOTE
Posts: 1403
Joined: 15 Jun 2015, 06:21

Re: Allman style v. K&R style/one true brace style

26 Oct 2019, 16:59

I vote for the Allman style. In fact, I use brackets even if one line of code, for clarity sake. Especially for troubleshooting or having to look at code months later. I think clarity is much more important than saving a few keystrokes. This also includes variable names, in my opinion, where you have one letter variables names versus descriptive variables names. I rather have the more descriptive variable name, as it makes code easier to understand and read.

The problem that I have with K&R, is the more lines of code, the more likely you are to have errors and mistakes. Using the Allman style, it's much easier to spot sections of code, understand it, and it decreases errors. Also the Allman style is closer to the indentation used in Object Pascal, another language that I like.

However, you do have to get yourself used to reading both styles, when looking at or using other people's code. Though if the amount of code borrowed is short enough, I will often convert the K&R style to Allman style. With this also having the added benefit of helping to more clearly understand each line of code that is being borrowed.
User avatar
Hellbent
Posts: 1886
Joined: 23 Sep 2017, 13:34

Re: Allman style v. K&R style/one true brace style

26 Oct 2019, 18:06

I have had a rather strange transition in the style I use.
I had started out with a indent style that looked like this.

Code: Select all

if(blah != blahblah)
	{
		blah := blahblahblah
		blahblah := !blahblah
		if(something)
			{
				NotSomething := DoSomething()
				if(!NotSomething)
					{
						return somethingelse
					}
				else
					{
						return blah
					}
			}
	}
So one might expect that if I was to change to another style I would go with Allman, but nope, went to K&R.
My only issue with it is that I have to add in Allman whenever I have to Parse lol.

I think that for me it boils down to the same reason that K&R became popular to begin with, getting more lines on the screen at once.
With my resolution I only get about 28 lines on my screen at once, 34 if I collapse ( the w/e you call the little debug dialog at the bottom of scite) after every time I run my code. Getting rid of a few extra lines might not seem like a big deal, but it really lowers the pain in my ass factor, and at the end of the day, anything that keeps that factor low helps to keep me pushing forward.

SOTE wrote:
26 Oct 2019, 16:59
In fact, I use brackets even if one line of code, for clarity sake. Especially for troubleshooting or having to look at code months later. I think clarity is much more important than saving a few keystrokes. This also includes variable names, in my opinion, where you have one letter variables names versus descriptive variables names. I rather have the more descriptive variable name, as it makes code easier to understand and read.
I'm with you there. Mind you, I do tend to pack the code up once I have it worked out.
"The box is an ant"
SOTE
Posts: 1403
Joined: 15 Jun 2015, 06:21

Re: Allman style v. K&R style/one true brace style

26 Oct 2019, 18:43

Hellbent, using your example, I tend to like aligning the brackets vertically and vertical alignment of code above the opening/top bracket. This has a more dramatic affect in AHK Studio, where the editor will show actual vertical lines connecting the brackets. It makes it much easier to identify sections of code and to make sure that sets of brackets match each other.

(Allman variation)

Code: Select all

if(blah != blahblah)
{
	blah := blahblahblah
	blahblah := !blahblah
	if(something)
	{
		NotSomething := DoSomething()
		if(!NotSomething)
		{
			return somethingelse
		}
		else
		{
			return blah
		}
	}
}
I also played with variations of Horstmann style, but found that brackets on the same line of code still had a tendency to create more silly errors or confusion, despite the benefit of the brackets and lines of code aligning vertically. However, liked this style more than K&R. The issue with this style is it works with C family languages, but doesn't work with Object Pascal (or other languages like Python, Lua, etc...), so that meant using an Allman-like style for consistency between the languages I like.

Note- in various non C family languages, you can get blocks of code to align vertically, which can also be done with the Allman style for C family languages (where both brackets and blocks of code can be aligned vertically, depending on how deeply nested).

(Horstmann variation in C language)

Code: Select all

while (x == y)
{	something();
	somethingelse();
	if (x < 0)
	{	printf("Negative");
		negative(x);
	}
	else
	{	printf("Non-negative");
		nonnegative(x);
	}
}
(Object Pascal Indentation as reference)

Code: Select all

procedure dosomething(x, y: Integer);
begin
	while x = y do
	begin
		something();
		somethingelse();
	end;
end;
(Lua Indentation as reference)

Code: Select all

local function paint(canvas, ntimes)
	for i=1,ntimes do
		local hello_str_asc_lc_en_const = "hello world"
		canvas:draw(hello_str_asc_lc_en_const:toupper())
	end
end
SOTE
Posts: 1403
Joined: 15 Jun 2015, 06:21

Re: Allman style v. K&R style/one true brace style

27 Oct 2019, 05:50

Nextron wrote:
10 May 2018, 16:15
If you don't indent or do it wrong, either style will be hard to read, although Allman will probably suffer less. I see indenting as the actual way to make code readable and braces just as an annoying requirement of the language, which I don't want to spend another dedicated line on by putting a opening brace on its own line, thereby stretching out the code.

I think Python manages this in an awesome way by making indentation levels functional by grouping lines into blocks. If that would be possible in AHK I would use it in a second.
Interestingly, I find the Python style of indentation extremely annoying and eye straining. Think that Python took it too far. I like seeing the C style brackets (or Pascal Begin/End equivalents of { }), as a way to visually group blocks of code. It's about more than just indenting, but also about easily identifiable visual grouping. I also believe Python's emphasis on white space leads to more errors, at least for beginners or casual users. In Python, an erroneous tab can be way more catastrophic than it arguably should be, where in other languages the missing indentations are not relevant.

Next on the list is arguably Lua. I'm not sure why it was thought having an "End", equivalent to "}" in C family languages, and no "Begin" (equivalent to "{" in C family languages) was a good idea. Maybe they just wanted to distinguish their code from Object Pascal/Delphi, which uses "Begin" and "End", but feel it wasn't a good idea. Debatably, Lua should have followed Pascal/Delphi (Begin and End) or C style brackets. Despite this, do think Lua code indentation is less eye straining than looking at Python, even if Python is more popular (though this might be due to country of origin).

I think for AHK, because it uses a C++ interpreter, using the C family style brackets was a great idea. Because this style lends itself to graduating to using other C family languages or editing the source code. I thought what AutoIt did was awful, using Basic-like syntax, but having C++ source code. Few are allowed to touch their source code, so it might seem to cancel the point, but Basic syntax is arguably less popular. The C family includes JavaScript, Java, C#, Objective C, Swift (new Apple created language), Dart (from Google), etc... I think being in the C family gives advanced AHK users an edge, if they ever decide to learn other languages, and makes reading code from other C family languages much easier.
User avatar
nnnik
Posts: 4497
Joined: 30 Sep 2013, 01:01
Location: Germany

Re: Allman style v. K&R style/one true brace style

13 Nov 2019, 03:28

To me Allman is harder to read than K&R. It all boils down to what you are used to. Im used to K&R like most other people on the discord. There is no objective advantage of one over the other.
Recommends AHK Studio

Return to “Offtopic”

Who is online

Users browsing this forum: No registered users and 6 guests