You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
There are many brace and indent styles in programming, but in the PowerShell community, there are essentially three:
BSD/Allman style
K&R/OTBS
Stroustroup
I've briefly given an example and explained the rationale for each below
Feel free to comment, but please vote for your favorite by using the 👍
And of course, if there's one you can't stand, feel free to give it a 👎
The Allman style is named after Eric Allman, who wrote many of the BSD utilities. It puts braces on their own lines, indented to the same level as the control statement, and indents statements within the braces.
This style is the Visual Studio default indenting style for C# and is the standard for dotnet, PowerShell, asp.net, and basically, all Microsoft C# projects.
enum Color
{
Black,
White
}
functionTest-Code
{
[CmdletBinding()]
param
(
[int]$ParameterOne
)
end
{
if(10-gt$ParameterOne)
{
"Greater"
}
else
{
"Lesser"
}
}
}
In PowerShell, braces sometimes are not for logic or flow-control, but function more like quotes: enclosing a script-block that you assign to a variable or pass as an argument. In those cases, the brace must be on the same line with the variable or command it's being passed to, so it will look wrong among Allman style indenting.
Built-in commands like ForEach-Object and Where-Object use script blocks as arguments, and there are a number of modules which emulate a sort-of DSL (Domain Specific Language) that require it as well, most prominently, Pester, which is shipped in Windows with PowerShell. Since most PowerShell coders who care about style are writing tests using Pester, the Allman style has had a disadvantage -- particularly since at PowerShell's beginning, Allman style didn't work for code you might want to type or paste into a command-line prompt.
Reacted by Jeremiah Salamon, Kevin Marquette, Travis Plunk, Brandon Padgett, Matt, My Random Thoughts, Warren Frame, Brian Marsh, jmonachesi, Trevor and 78 more
Reacted by Mikey Lombardi (He/Him), Kevin Kirkpatrick, Eric S. Weilnau, Joshua Poehls, Dominique Broeglin, Adam Bertram, Mark Wragg, Devin W. Leaman, ckennedy666, shinjijai and 45 more
Reacted by Magnus Meyer Hustveit, Trevor, Ben Wilkinson, hypercube33, metablaster and Cody Hunsberger
K&R is named for Kernighan and Ritchie, who used it in their book The C Programming Language. According to Wikipedia it originated in Kernighan and Plauger's The Elements of Programming Style and Software Tools. It puts braces on the same line as control statements.
The One True Brace Style is the K&R style with every braceable statement always having the brace on the end of the line. The original K&R puts braces for functions on a new line, and gave you the option to leave off braces for one-line statement blocks (which you cannot do in PowerShell).
enum Color {
Black,
White
}
functionTest-Code {
[CmdletBinding()]
param(
[int]$ParameterOne
)
end {
if (10-gt$ParameterOne) {
"Greater"
} else {
"Lesser"
}
}
}
The primary argument for OTBS is practical: when code is written following this style, new lines of code can be inserted between any two lines with no risk of accidentally breaking the code by separating braces from their statement blocks.
In PowerShell, this style gained many adherents early on, because prior to the arrival of the ISE in PowerShell 3 and later the PSReadLine module, it simply wasn't possible to put most braces on a new line when typing them into the console, and this was the only place you could type that knew anything about the language! The console expected a single line of PowerShell, and would produce errors if, for instance, you didn't put a { at the end of the line after an if(...) block.
Reacted by Chris Dent, Joel Bennett, Kevin Kirkpatrick, Rudy Schockaert, Adam Platt, Matthew Johnson, Carlos Perez, Rafael Dowling Goodman, Dave Hull, Mikey Lombardi (He/Him) and 171 more
Reacted by Travis Plunk, Brandon Padgett, My Random Thoughts, Warren Frame, jmonachesi, Trevor, Philip Meholm, Magnus Meyer Hustveit, Simon Watson, ALIENQuake and 26 more
Reacted by CharlieRussel, Javier Perez, Kris Borowinski, Non, Raiden Erdmann, Marius Storhaug, Eidmone Tagaca and masterflitzer
Named after Bjarne Stroustrup, who created it while writing his Programming: Principles and Practice using C++ and The C++ Programming Language, this style is a long time favorite of those who learned C++ as their first language. It is essentially a variant on K&R discussed earlier, with some variations: "else" blocks are placed on a new line. Unlike the OTBS variation, it follows K&R's suggestion that although the opening brace for a class and a struct are not on a separate line, for a function it is. It also allows skipping the braces for single line statements, but that's not allowed by PowerShell's parser.
enum Color {
Black,
White
}
functionTest-Code
{
[CmdletBinding()]
param(
[int]$ParameterOne
)
end {
if(10-gt$ParameterOne) {
"Greater"
}
else {
"Lesser"
}
}
}
The changes Stroustrup makes means that this style looses the "insert a line anywhere" feature of OTBS, and looks somewhat like a cross between Allman and OTBS.
Reacted by Troy Campbell, Chris Gardner, Anders Wahlqvist, Chris Warwick, Marco Blessing, shinjijai, Ben Gould, Mathieu BUISSON, Jade, Ioan Popovici and 10 more
Reacted by Adam Platt, Brandon Padgett, Adam Bertram, Chris Warwick, Matt, My Random Thoughts, Trevor, Dave Kaylor, Denis Plekhov, Philip Meholm and 53 more
Reacted by Joel Bennett, Mikey Lombardi (He/Him), Travis Plunk, Brian Marsh, ALIENQuake, Trevor, Tom-Inge Larsen, Cameron, Oliver Lipkau, CharlieRussel and 3 more
It appears to me that PowerShell advocates of "Stroustrup style" don't actually care for anything he says except having the else on a new line. Other than that, they want to follow OTBS. If that's true for you... vote here instead of there ;-)
Reacted by Rudy Schockaert, Andrew Childs, Mark Roloff, Steve Lowe, Keith Hill, Jared Haight, Jason Cole, James Ruskin, Lewis Roberts, Chris Warwick and 63 more
P.S. As a side note (and I will brook no discussion on this): spaces won. In this guide, an indentation level is 4 spaces.
For thoroughness, I reviewed C, C++, BSD, Linux kernel, Google's JavaGuide and the dotnet, asp.net, and PowerShell guides -- they all use spaces, except the Linux Kernel. Google's Java guide uses 2 spaces. All of the others use 4 spaces.
The kernel coding style guide, being written by a dictator who still codes in a terminal, not only requires tabs, it specifies tabs as 8 characters, limits line length to 80 characters, and considers anything over 3 levels of indent to be a design flaw. It also refers to K&R as prophets, and to those who disagree with K&R as heretics, and considers the violation of naming conventions a "shooting offense" ...
Reacted by Keith Hill, Carlos Perez, Mikey Lombardi (He/Him), Rudy Schockaert, Ioan Popovici, Michael Romancuk, Tom-Inge Larsen, Maximilian Orsley, Rain Sallow (/u/ta11ow), Bradley Jones and 11 more
Reacted by jwmarrott, John J Kavanagh, Pharap, Iggy, Andreas Hjelming and redbeardt
Reacted by Elle, Ioan Popovici, maelcum, Rain Sallow (/u/ta11ow), chrisranney, Maximilian Orsley, Non and Ryan
P.P.S. The Linux Kernel advocates for the pure K&R indentation style, with neither the OTBS variation forced upon PowerShell in the early days, nor Stroustrup's lonely else, in defense of this difference between function braces and everything else, they write:
Unlike the indent size, there are few technical reasons to choose one
[brace] placement strategy over the other, but the preferred way, as
shown to us by the prophets Kernighan and Ritchie, is to put the opening
brace last on the line, and put the closing brace first ...
Heretic people all over the world have claimed that this inconsistency
is ... well ... inconsistent, but all right-thinking people know that
(a) K&R are right and (b) K&R are right. Besides, functions are
special anyway (you can't nest them in C).
This was the best defense I found for that oddity of K&R's bracing style.
Obviously in the C# and PowerShell world, K&R are not considered "prophets" and the Allman style prevails -- but additionally, it's worth pointing out that functions are not special in PowerShell: they can be nested.
This may be sufficient reason for the PowerShell variant of Stroustrup's variant to choose to treat the braces for functions the same as other braces (putting them at the end of the line), but when combined with the prohibition on leaving braces off, it certainly argues that this PowerShell-Stroustrup style is no longer the C++ standard style, but something invented by PowerShell programmers....
Even though I had no idea what is OTBS I mostly use it in my code. I prefer it cause it is neat. Since most PowerShell function are really simple and short, scrolling tons of braces doesn't seem convenient.
Reacted by Dominik Gauss, Herb Martin and Plínio Larrubia
I use OTBS with Stroustrup else. I believe i started my programming/scripting foray with PHP so it may have started there but I carried it in to VBscript and Powershell. Allman style is a waste of space, literally rather than figuratively, and OTBS with else on the same line is just unnecessarily confusing compared to the rest of the script. That's my two pence...🇬🇧
Reacted by Devin W. Leaman, Andrew Childs, Kapil Borle, Bill Stewart, Ben Gould, Ioan Popovici, Keith Hill, Cosmin, shinjijai, Tom-Inge Larsen and 15 more
P.S. As a side note (and I will brook no discussion on this): spaces won. In this guide, an indentation level is 4 spaces.
4 spaces is 2 too many.
Reacted by Brett Veenstra, Patrick Meunier, RJ Cuthbertson, Mikey Lombardi (He/Him), Bill Stewart, fromthewoods, moosedookie, Joseph Petersen, Richard Vrijhof, Brian Stringfellow and 10 more
Reacted by Ioan Popovici, Gavin Eke, biddster, Cosmin, Rain Sallow (/u/ta11ow), nicasi, Keith Hill, Cameron, jwmarrott, moocowcat and 12 more
Reacted by Mikey Lombardi (He/Him), Joel Bennett, Glen Buktenica, Chia-Sheng Chen and Fab Ian Fuerste
PowerShell doesn't use Allman style. It uses C#/.NET style (which is Allman style). So one degree of indirection. PowerShell is conventionally indented with 4 spaces because Windows. I came from a Unix background (East coast, Murray Hill by way of University of Wateroo) where we used OTBS and tabs. With tabs, you could set your editor to display 2, 4, 8 or however many spaces you wanted. Much less cursoring about too.
Reacted by Mikey Lombardi (He/Him), chrisranney, Rain Sallow (/u/ta11ow), John, John J Kavanagh, Raymond Piller, Nato Boram, robinmalik, Matt Dunlap and redbeardt
Reacted by Rich Siegel, moocowcat and Maximilian Orsley
As Mr. Bennett noted, we can't use C#/.NET/Allman/Whitesmiths with cmdlets that use a scriptblock, as in:
Get-ChildItem C:\Windows | ForEach-Object
{
...
}
... due to the fact that the cmdlet needs the scriptblock as its next token (we can use `, but that adds ugliness and inconsistency). I can see advantages of the Whitesmiths style (e.g. see here), but for consistent look, it would seem we have to use some variant of OTBS.
My current preference is OTBS without the "cuddled else" (the "cuddled else" looks inconsistent IMO), with two spaces for indentation. (I don't understand why using more than 2 spaces is necessary. Perhaps someone could explain?)
@Bill-Stewart 2 space indentation is something I've seen in serialized languages (such as XML), but no where else. I suspect because the code is less readable with everything scrunched together and a lack of whitespace.
Reacted by John J Kavanagh, Pharap, Glen Buktenica, Frederik Krautwald, robinmalik and Lemmingh
That's not actually true @mklement0, PSReadLine's paste functionality works the same on Linux, unless your terminal intercepts the Ctrl+V hotkey (in which case, change it to Ctrl+Shift+V in PSReadLine 😉)
You shouldn't have to redefine or define alternativse to whatever your terminal's paste-from-clipboard shortcut is - or any of its other, menu-based paste methods (which you probably can't redefine).
Similarly, right-clicking on Windows should work just like Ctrl+V pasting.
That is, while a given terminal may paste by simulating keystrokes, which is outside of PSReadLine's immediate control, a fix is - fortunately - still planned: PowerShell/PSReadLine#579
I initially wanted to explain the discrepancy between @VertigoRay's experience on the one hand, and @rkeithhill and @Bill-Stewart's on the other (or to at least show that there are scenarios where the behavior is platform-dependent).
Once Right click paste should work mostly like Ctrl+v paste PowerShell/PSReadLine#579 is addressed, the terminals on all platforms should be able to handle pasting multi-line if statements at the prompt in which else is on its own line (Allman and Stroustrup styles).
However, you can't interactively type statements in this style, unless you use Shift+Enter to explicitly continue on the next line, as mentioned by @rkeithhill, which only seems to work (at least out of the box) on Windows.
Shift+Enter also depends on the terminal, because VT doesn't send "Shift" as a key press, and there's no capital Enter 😉 (it doesn't even work in Windows Terminal)
That's good to know, @Jaykul (I realized I had gone down that rabbit hole before, and I've just summarized what - limited - set of chords are actually usable with Set-PSReadLineKeyHandler on Unix-like platforms here).
Not being able to use the same key chord on all platforms is an additional annoyance, but I think the fundamental (but unavoidable) problem is having to remember that and when to add a line explicitly using a different key chord is necessary, which makes else-on-a-new-line styles fundamentally inconvenient for typing a multi-line command (but hopefully the fix to #579 will make pasting work).
At the end of the day, most people don't switch operating systems or terminals very often -- so switching and needing to change your configuration may be annoying, but it isn't common 😉
Figure out what your most restrictive platform can handle (pwsh on Unix over VT, from inside bash) and configure something that works -- then use it everywhere.
Regardless, I think whether the default hotkeys for PSReadLine work (or not) is basically irrelevant to the community's choice about code formatting -- people who are trying to use PSReadLine to justify choosing something other than OTBS obviously don't care about other hosts and experiences without PSReadLine 😉
Activity
Jaykul commentedon Mar 11, 2017
Allman style
The Allman style is named after Eric Allman, who wrote many of the BSD utilities. It puts braces on their own lines, indented to the same level as the control statement, and indents statements within the braces.
This style is the Visual Studio default indenting style for C# and is the standard for dotnet, PowerShell, asp.net, and basically, all Microsoft C# projects.
enum Color { Black, White } function Test-Code { [CmdletBinding()] param ( [int]$ParameterOne ) end { if(10 -gt $ParameterOne) { "Greater" } else { "Lesser" } } }In PowerShell, braces sometimes are not for logic or flow-control, but function more like quotes: enclosing a script-block that you assign to a variable or pass as an argument. In those cases, the brace must be on the same line with the variable or command it's being passed to, so it will look wrong among Allman style indenting.
Built-in commands like
ForEach-ObjectandWhere-Objectuse script blocks as arguments, and there are a number of modules which emulate a sort-of DSL (Domain Specific Language) that require it as well, most prominently, Pester, which is shipped in Windows with PowerShell. Since most PowerShell coders who care about style are writing tests using Pester, the Allman style has had a disadvantage -- particularly since at PowerShell's beginning, Allman style didn't work for code you might want to type or paste into a command-line prompt.Jaykul commentedon Mar 11, 2017
K&R (One True Brace Style variant)
K&R is named for Kernighan and Ritchie, who used it in their book The C Programming Language. According to Wikipedia it originated in Kernighan and Plauger's The Elements of Programming Style and Software Tools. It puts braces on the same line as control statements.
The One True Brace Style is the K&R style with every braceable statement always having the brace on the end of the line. The original K&R puts braces for functions on a new line, and gave you the option to leave off braces for one-line statement blocks (which you cannot do in PowerShell).
enum Color { Black, White } function Test-Code { [CmdletBinding()] param( [int]$ParameterOne ) end { if (10 -gt $ParameterOne) { "Greater" } else { "Lesser" } } }The primary argument for OTBS is practical: when code is written following this style, new lines of code can be inserted between any two lines with no risk of accidentally breaking the code by separating braces from their statement blocks.
In PowerShell, this style gained many adherents early on, because prior to the arrival of the ISE in PowerShell 3 and later the PSReadLine module, it simply wasn't possible to put most braces on a new line when typing them into the console, and this was the only place you could type that knew anything about the language! The console expected a single line of PowerShell, and would produce errors if, for instance, you didn't put a
{at the end of the line after anif(...)block.Jaykul commentedon Mar 11, 2017
Stroustrup
Named after Bjarne Stroustrup, who created it while writing his Programming: Principles and Practice using C++ and The C++ Programming Language, this style is a long time favorite of those who learned C++ as their first language. It is essentially a variant on K&R discussed earlier, with some variations: "else" blocks are placed on a new line. Unlike the OTBS variation, it follows K&R's suggestion that although the opening brace for a class and a struct are not on a separate line, for a function it is. It also allows skipping the braces for single line statements, but that's not allowed by PowerShell's parser.
enum Color { Black, White } function Test-Code { [CmdletBinding()] param( [int]$ParameterOne ) end { if(10 -gt $ParameterOne) { "Greater" } else { "Lesser" } } }The changes Stroustrup makes means that this style looses the "insert a line anywhere" feature of OTBS, and looks somewhat like a cross between Allman and OTBS.
Jaykul commentedon Mar 11, 2017
It appears to me that PowerShell advocates of "Stroustrup style" don't actually care for anything he says except having the
elseon a new line. Other than that, they want to follow OTBS. If that's true for you... vote here instead of there ;-)Jaykul commentedon Mar 11, 2017
P.S. As a side note (and I will brook no discussion on this): spaces won. In this guide, an indentation level is 4 spaces.
For thoroughness, I reviewed C, C++, BSD, Linux kernel, Google's JavaGuide and the dotnet, asp.net, and PowerShell guides -- they all use spaces, except the Linux Kernel. Google's Java guide uses 2 spaces. All of the others use 4 spaces.
The kernel coding style guide, being written by a dictator who still codes in a terminal, not only requires tabs, it specifies tabs as 8 characters, limits line length to 80 characters, and considers anything over 3 levels of indent to be a design flaw. It also refers to K&R as prophets, and to those who disagree with K&R as heretics, and considers the violation of naming conventions a "shooting offense" ...
Jaykul commentedon Mar 11, 2017
P.P.S. The Linux Kernel advocates for the pure K&R indentation style, with neither the OTBS variation forced upon PowerShell in the early days, nor Stroustrup's lonely else, in defense of this difference between function braces and everything else, they write:
This was the best defense I found for that oddity of K&R's bracing style.
Obviously in the C# and PowerShell world, K&R are not considered "prophets" and the Allman style prevails -- but additionally, it's worth pointing out that functions are not special in PowerShell: they can be nested.
This may be sufficient reason for the PowerShell variant of Stroustrup's variant to choose to treat the braces for functions the same as other braces (putting them at the end of the line), but when combined with the prohibition on leaving braces off, it certainly argues that this PowerShell-Stroustrup style is no longer the C++ standard style, but something invented by PowerShell programmers....
sergeytunnik commentedon Mar 14, 2017
Even though I had no idea what is OTBS I mostly use it in my code. I prefer it cause it is neat. Since most PowerShell function are really simple and short, scrolling tons of braces doesn't seem convenient.
lwsrbrts commentedon Mar 17, 2017
I use OTBS with Stroustrup else. I believe i started my programming/scripting foray with PHP so it may have started there but I carried it in to VBscript and Powershell. Allman style is a waste of space, literally rather than figuratively, and OTBS with else on the same line is just unnecessarily confusing compared to the rest of the script. That's my two pence...🇬🇧
TimCurwick commentedon Jun 1, 2017
I use Allman style when writing code for clients and sometimes for colleagues. I use a variant on Allman when I don't care about anyone else.
rismoney commentedon Aug 1, 2017
4 spaces is 2 too many.
define VS Code PowerShell bracing style and set itDto Stroustrup: Pos…
Minor code formatting
BrucePay commentedon Apr 24, 2018
PowerShell doesn't use Allman style. It uses C#/.NET style (which is Allman style). So one degree of indirection. PowerShell is conventionally indented with 4 spaces because Windows. I came from a Unix background (East coast, Murray Hill by way of University of Wateroo) where we used OTBS and tabs. With tabs, you could set your editor to display 2, 4, 8 or however many spaces you wanted. Much less cursoring about too.
Bill-Stewart commentedon Aug 6, 2018
As Mr. Bennett noted, we can't use C#/.NET/Allman/Whitesmiths with cmdlets that use a scriptblock, as in:
... due to the fact that the cmdlet needs the scriptblock as its next token (we can use
`, but that adds ugliness and inconsistency). I can see advantages of the Whitesmiths style (e.g. see here), but for consistent look, it would seem we have to use some variant of OTBS.My current preference is OTBS without the "cuddled else" (the "cuddled else" looks inconsistent IMO), with two spaces for indentation. (I don't understand why using more than 2 spaces is necessary. Perhaps someone could explain?)
morsley commentedon Aug 22, 2018
@Bill-Stewart 2 space indentation is something I've seen in serialized languages (such as XML), but no where else. I suspect because the code is less readable with everything scrunched together and a lack of whitespace.
10 remaining items
Bill-Stewart commentedon Jul 3, 2019
Not sure what you mean; that code works fine (syntax-wise) when posted into a console.
rkeithhill commentedon Jul 3, 2019
Yup, pasting that syntax has worked for a while now - ever since we got PSReadLine.
You don't even have to be pasting. You can even type in the above if you use shift+enter to start a new line for the
else.use OTBS code formatting
use OTBS code formatting
use OTBS code formatting
vscode formatting (#83)
mklement0 commentedon Dec 20, 2019
That indeed works well on Windows, @rkeithhill and @Bill-Stewart but not on Unix-like platforms, as of PSReadLine v2.0-rc1 - see PowerShell/PSReadLine#1261
Jaykul commentedon Dec 24, 2019
That's not actually true @mklement0, PSReadLine's paste functionality works the same on Linux, unless your terminal intercepts the Ctrl+V hotkey (in which case, change it to Ctrl+Shift+V in PSReadLine 😉)
mklement0 commentedon Dec 24, 2019
@Jaykul:
You shouldn't have to redefine or define alternativse to whatever your terminal's paste-from-clipboard shortcut is - or any of its other, menu-based paste methods (which you probably can't redefine).
Similarly, right-clicking on Windows should work just like Ctrl+V pasting.
That is, while a given terminal may paste by simulating keystrokes, which is outside of PSReadLine's immediate control, a fix is - fortunately - still planned: PowerShell/PSReadLine#579
To quote @lzybkr from that issue (PowerShell/PSReadLine#579 (comment)):
And said heuristic approach is fleshed out more in PowerShell/PSReadLine#579 (comment)
mklement0 commentedon Dec 24, 2019
The bottom line is:
I initially wanted to explain the discrepancy between @VertigoRay's experience on the one hand, and @rkeithhill and @Bill-Stewart's on the other (or to at least show that there are scenarios where the behavior is platform-dependent).
Once Right click paste should work mostly like Ctrl+v paste PowerShell/PSReadLine#579 is addressed, the terminals on all platforms should be able to handle pasting multi-line
ifstatements at the prompt in whichelseis on its own line (Allman and Stroustrup styles).However, you can't interactively type statements in this style, unless you use Shift+Enter to explicitly continue on the next line, as mentioned by @rkeithhill, which only seems to work (at least out of the box) on Windows.
Jaykul commentedon Dec 24, 2019
Shift+Enter also depends on the terminal, because VT doesn't send "Shift" as a key press, and there's no capital Enter 😉 (it doesn't even work in Windows Terminal)
mklement0 commentedon Dec 24, 2019
That's good to know, @Jaykul (I realized I had gone down that rabbit hole before, and I've just summarized what - limited - set of chords are actually usable with
Set-PSReadLineKeyHandleron Unix-like platforms here).Not being able to use the same key chord on all platforms is an additional annoyance, but I think the fundamental (but unavoidable) problem is having to remember that and when to add a line explicitly using a different key chord is necessary, which makes
else-on-a-new-line styles fundamentally inconvenient for typing a multi-line command (but hopefully the fix to #579 will make pasting work).Jaykul commentedon Dec 25, 2019
At the end of the day, most people don't switch operating systems or terminals very often -- so switching and needing to change your configuration may be annoying, but it isn't common 😉
Figure out what your most restrictive platform can handle (pwsh on Unix over VT, from inside bash) and configure something that works -- then use it everywhere.
Regardless, I think whether the default hotkeys for PSReadLine work (or not) is basically irrelevant to the community's choice about code formatting -- people who are trying to use PSReadLine to justify choosing something other than OTBS obviously don't care about other hosts and experiences without PSReadLine 😉