Skip to content

Where to put braces #24

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Jaykul opened this issue May 29, 2015 · 35 comments
Closed

Where to put braces #24

Jaykul opened this issue May 29, 2015 · 35 comments
Labels

Comments

@Jaykul
Copy link
Member

Jaykul commented May 29, 2015

Option One: Same Line

function Get-Noun {
    end {
        if($Wide) {
            Get-Command | Sort-Object Noun -Unique | Format-Wide Noun
        } else {
            Get-Command | Sort-Object Noun -Unique | Select-Object -Expand Noun
        }
    }
}

Option Two: New Line

function Get-Noun
{
    end
    {
        if($Wide)
        {
            Get-Command | Sort-Object Noun -Unique | Format-Wide Noun
        }
        else
        {
            Get-Command | Sort-Object Noun -Unique | Select-Object -Expand Noun
        }
    }
}

I deliberately left out the param block just to make sure we don't get distracted and argue about it.

@mwjcomputing
Copy link

Completely option 1. Cleaner.

Matt Johnson
MWJ Computing
734-323-3235
[email protected]:[email protected]
www.mwjcomputing.comhttp://www.mwjcomputing.com
@mwjcomputing

Sent from my iPwn

On May 29, 2015, at 11:16 AM, Joel Bennett <[email protected]mailto:[email protected]> wrote:

Option One: Same Line

function Get-Noun {
end {
if($Wide) {
Get-Command | Sort-Object Noun -Unique | Format-Wide Noun
} else {
Get-Command | Sort-Object Noun -Unique | Select-Object -Expand Noun
}
}
}

Option Two: New Line

function Get-Noun
{
end
{
if($Wide)
{
Get-Command | Sort-Object Noun -Unique | Format-Wide Noun
}
else
{
Get-Command | Sort-Object Noun -Unique | Select-Object -Expand Noun
}
}
}

I deliberately left out the param block just to make sure we don't get distracted and argue about it.

Reply to this email directly or view it on GitHubhttps://github.com//issues/24.

@nightroman
Copy link

Option 1. Because it uses the same style as a script block specified as a command parameter. In the latter case we do not have a choice.

Example. task is a command (DSL) with syntax task [string]$Name [scriptblock]$Action:

task Build {
    MSBuild ....
}

UPDATE: I prefer 1.5 (see below). } else { looks not good and more difficult to cut, paste, delete as a block of code.

@RamblingCookieMonster
Copy link

I would recommend including both as options, provided consistent use across a code base.

Both styles have positives and negatives. Neither is inherently better. Also, if you specify one, you might start a holy war.

Cheers!

@sunmorgus
Copy link

Both need to be an option. In-line works very well for most things, but I feel as though having the else on the same line makes that if-else statement harder to parse. Typically, I use a combination similar to this:

function Get-Noun {
    end {
        if($Wide) {
            Get-Command | Sort-Object Noun -Unique | Format-Wide Noun
        }
        else {
            Get-Command | Sort-Object Noun -Unique | Select-Object -Expand Noun
        }
    }
}

@mikefrobbins
Copy link

I write my PowerShell code using option 1 (curly brace on same line). Why? Because I like to use one standard consistently no mater what command is being used.

Since there is no option with commands like ForEach-Object, Where-Object, etc and the curly brace must be on the same line:

$b | ForEach-Object {
    #code
}

I also write code that uses commands such as the foreach scripting construct using this same standard:

foreach ($a in $b) {
    #code
}

Otherwise I would have code written using two different standards. Some with the curly brace on the same line:

$b | ForEach-Object {
    #code
}

And some with the curly brace on a different line:

foreach ($a in $b)
{
    #code
}

Hopefully that makes sense and helps others to understand why I pick the only option that allows for a single standard to be used throughout your code regardless of the command that is being used.

µ

@rkeithhill
Copy link

I agree with @sunmorgus, I'd go for option 1.5 - Stroustrup style (no cuddled else):

function Get-Noun {
    end {
        if($Wide) {
            Get-Command | Sort-Object Noun -Unique | Format-Wide Noun
        } 
        else {
            Get-Command | Sort-Object Noun -Unique | Select-Object -Expand Noun
        }
    }
}

I don't like cuddled else and catch. It's easier IMO to line-select a whole else clause and delete it. With K&R style, you can easily wind up deleting the closing } on the if statement.

@KirkMunro
Copy link
Contributor

Option 1, with "cuddled" (didn't know that was the term) else/catch/finally. I prefer that style because visually only new commands start a line with an alphabetic character (which is also why I prefer pipelines spanning multiple lines starting the 2nd, 3rd, etc lines with | symbols). It provides better consistency across all lines of script this way.

-----Original Message-----
From: "Keith Hill" [email protected]
Sent: ‎2015-‎05-‎29 12:13 PM
To: "PoshCode/PSStyleGuide" [email protected]
Subject: Re: [PSStyleGuide] Where to put braces (#24)

I'd go for option 1.5 - Stroustrup style (no cuddled else):
function Get-Noun {
end {
if($Wide) {
Get-Command | Sort-Object Noun -Unique | Format-Wide Noun
}
else {
Get-Command | Sort-Object Noun -Unique | Select-Object -Expand Noun
}
}
}I don't like cuddled else and catch. It's easier IMO to line-select a whole else clause and delete it. With K&R style, you can easily wind up deleting the closing } on the if statement.

Reply to this email directly or view it on GitHub.

@mikefrobbins
Copy link

I prefer option 1.5 as well.

@theJasonHelmick
Copy link

Agree with MikeFRobbins and SunMorgus - 1.5 - love the cuddling around this place ;)

@mwjcomputing
Copy link

I like 1.5 as well.

One thing to note is that ISESteroids does #2 when you run the refactoring tool.

On May 29, 2015, at 12:28 PM, theJasonHelmick <[email protected]mailto:[email protected]> wrote:

Agree with MikeFRobbins and SunMorgus - 1.5 - love the cuddling around this place ;)


Reply to this email directly or view it on GitHubhttps://github.com//issues/24#issuecomment-106864384.

@bigoals365
Copy link

Awwww A big old fashion PowerShell cuddle pile :}
1.5 rocks

@kefoster
Copy link

Option 1

@jrich523
Copy link

i prefer option 2, i think its faster for me to scan and find the blocks. however the point of @nightroman is valid, which i also found with Pester..

so that being said, i think both should be valid

@darkoperator
Copy link
Contributor

Are we really gonna go down rabbit holes like where put the brace? I go with option 2 it is the default in the ISE that comes from MS and it is the same I follow unless forced to by Java or something else. Include both.

On May 29, 2015, at 12:49 PM, Kevin Foster [email protected] wrote:

Option 1


Reply to this email directly or view it on GitHub #24 (comment).

@KirkMunro
Copy link
Contributor

Not that I want to debate this issue (I really, really don't). but @darkoperator, I have to ask: how is option 2 "the default in ISE that comes from MS"? ISE without add-ons doesn't force a default brace style at all as far I can tell.

@darkoperator
Copy link
Contributor

The default in snippets

On May 29, 2015, at 9:33 PM, Kirk Munro [email protected] wrote:

doesn't

@KirkMunro
Copy link
Contributor

Ok. Thanks for pointing out the source of your comment. I personally wouldn't draw from the style used in ISE Snippets as the defacto style guide to follow for everything PowerShell, but maybe that's just me.

@darkoperator
Copy link
Contributor

That is why I would rather both options be included we each have our reasons, Just like where to put comments blocks, I hate the idea of having them inside a function, but others like it, functional wise does it make a diff? no, does it make it more difficult to understand? no, does it make it more difficult to maintain? no, would it make it lead to problem across version or execution/security/functional/performance problems? no I would suggest the main focus should be on that practices that would have an impact and let the rest to the individual person to decide.

On May 29, 2015, at 9:47 PM, Kirk Munro [email protected] wrote:

Ok. Thanks for pointing out the source of your comment. I personally wouldn't draw from the style used in ISE Snippets as the defacto style guide to follow for everything PowerShell, but maybe that's just me.


Reply to this email directly or view it on GitHub #24 (comment).

@rkeithhill
Copy link

@darkoperator RE hate the idea of having them inside a function - I absolutely agree. But then that is probably 30 some years of C/C++/C# experience talking - saying that function comments go outside and above the function. :-)

@Jaykul
Copy link
Member Author

Jaykul commented May 30, 2015

@darkoperator I agree. I posted this here to remove it from the other conversation, but like I said to you last week, I don't want to put anything in here unless we have a general consensus about it.

Things that we have general disagreement about, where we have lots of different opinions, or a schism between two options, are not worth specifying in a community style guide. If individual projects want to exercise detailed control, more power to them -- but if we don't have a general agreement, or at least a quorum, the best we can do is document all the good choices (which doesn't seem particularly useful, especially for stuff like braces).

P.S. For what it's worth, I prefer 1.

I don't like 1.5 or 2 because you can't type like that in a console (or copy-paste code like that):

if(Test-Path $Home\Projects) {
    Get-ChildItem $Home\Projects
}
else { 
    Write-Warning "We don't know where your projects are"
}

PowerShell would run the first if and then report that else isn't a valid command.

I actually preferred that style in C#, but when I can, I want to write PowerShell the same way regardless of where I'm typing, and not have to remember to change style when I'm in the console.

@Jaykul
Copy link
Member Author

Jaykul commented May 30, 2015

By the way, all of the rest of you that @RamblingCookieMonster dragged in here off Twitter -- please do read some of the documents and issues and get involved in more worthwhile debates 😉

@Jaykul Jaykul added the invalid label May 30, 2015
@mikefrobbins
Copy link

One point I wanted to add here is regardless of which style you prefer and/or use, if you're contributing to a project such as one on GitHub, you should write your code using the style that the author of the project is using if you plan to request that your changes be merged back into the original source.

@KirkMunro
Copy link
Contributor

@Jaykul: I disliked 1.5 and 2 for the same reason, but then I thought I should check to make sure. Turns out that you can type like that in a console and you can copy/paste those formats and they work just fine. I still find it unnatural when opening curly braces at the end of a line because visually it looks like a new command to me, but copy/paste and typing into the console like that works.

@Jaykul
Copy link
Member Author

Jaykul commented May 30, 2015

@KirkMunro Funny part about that is that I tested it before I wrote that -- but I had a clipboard helper (which I forgot about years ago) which lets me Ctrl+V into Powershell -- it was interfering with PSReadLine's new Ctrl+V support. Right click (and PSReadLine's Ctrl+V, of course) let it work. So I'll withdraw my objection to 1.5 -- 2 is still awful 😛

@DexterPOSH
Copy link

I used to follow 2 style but since I started writing Pester tests aligning more towards 1.5 style nowadays.

@sqlchow
Copy link

sqlchow commented May 31, 2015

I came across the following Coding-Style: Should curly braces appear on their own line, on stackexchange.

personally, I think 1.5 is a better option.

@KirkMunro
Copy link
Contributor

Yuck, that's a horrible example to folow. Function params should be in a
param statement inside the function, *not *in round brackets outside the
function. Code is much cleaner, plus there is at least one limitation when
you use round brackets vs the param statement (can't remember what that is
right now). When you use a param statement, there is no question where the
function begins/ends, and none of this ugly wrapping nonsense with
arguments that curly braces should be on their own line as a result of the
ugliness. :)

*Kirk Munro *
Poshoholic, Microsoft MVP
Blog http://poshoholic.com/ | Twitter http://twitter.com/poshoholic |
LinkedIn http://ca.linkedin.com/in/kirkmunro | GitHub
http://github.com/KirkMunro | Facebook
http://www.facebook.com/#%21/kirk.munro

Need a PowerShell SME for a project at work? Contact me
http://poshoholic.com/contact-me/!

On Sun, May 31, 2015 at 1:20 PM, sqlchow [email protected] wrote:

I came across the following Coding-Style: Should curly braces appear on
their own line http://programmers.stackexchange.com/a/2786, on
stackexchange.

personally, I think 1.5 is a better option.


Reply to this email directly or view it on GitHub
#24 (comment)
.

@KirkMunro
Copy link
Contributor

While this is marked as invalid, I just ran into something with a script from another community member that made me want to come back with an additional comment that may lean this towards a best practice.

If you are copying and pasting code into a PowerShell host, the only way that you can guarantee that code will execute as it was written, according to how braces are used at least, is if you use option 1.

For example, copying and pasting this into PowerShell won't work:

$something = $false

# This is the if statement
if ($something) {
    'If'
}

# This is the else clause
else {
    'Else'
}

Nor will this:

try {
    throw 'Something'
}

catch [System.Exception] {
    'type-specific catch'
}

catch {
    'catch all'
}

Those will fail to run when pasted in the native shell, unless you use PSReadline with Ctrl+V. The reason the paste fails is because as items are pasted in, when a blank line is encountered the parser fails to identify that the current command isn't finished yet. Compare that with style 1, with "cuddled" else/catch statements, where commands paste properly because you can't put a newline in that may/may not break the command unless it changes how the curly braces are formatted.

Anyhow, this can stay in the "invalid" category, but I felt it was worth adding this additional info for perspective on why style 1 may be worth considering over the others for users who are not yet decided on how they want to format with braces yet.

@mrbodean
Copy link
Contributor

mrbodean commented Oct 7, 2015

I agree with RamblingCookieMonster and a few others. As long as the same style is used consistently, use the option that you prefer.

@mnaoumov
Copy link

mnaoumov commented Apr 29, 2016

I am a big fan of option 2 (according to wiki, it is called Allman style or BSD style). I used to it in C#

So I am forcing it in PowerShell as well, as there is no obvious well-defined style. Like in JavaScript, it's default K&R 1TBS (see wiki link above).

Some commenters mentioned inability to use scripblocks as the drawback of the option 2. Well, it's partially true but there is a workaround with backtick

task Build `
  {
      MSBuild ....
  }

I've seen some recommendations to not use backtick symbol but I believe it's very useful to gain better readability in such cases

Invoke-MyCmdlet `
    -Parameter1 "Very long parameter" `
    -Parameter2 "Another very long parameter" `
    -ScriptBlock3 `
        {
            # some action
        }

UPD:: I kept reading the site and found advice against backticks in further section...

@Jaykul
Copy link
Member Author

Jaykul commented Apr 29, 2016

Why would you want to adopt a syntax that requires workarounds? ;-)

@mnaoumov
Copy link

@Jaykul That's a very strong point which I can't beat :)

@Jaykul
Copy link
Member Author

Jaykul commented Mar 11, 2017

Just for fun, I'm going to close this and open a new one now that we have a way to count votes ;-)

@Jaykul Jaykul closed this as completed Mar 11, 2017
@Dearl1988
Copy link

Option 2 all the way... It is cleaner, even though bigger... It makes code easier to read.

@chriskuech
Copy link

Reading this thread, it sounds like this TODO can be removed from https://github.com/PoshCode/PowerShellPracticeAndStyle/blob/master/Style-Guide/Code-Layout-and-Formatting.md ?

1RedOne added a commit to 1RedOne/PowerShellPracticeAndStyle that referenced this issue Oct 2, 2018
Seemed like the life of this discussion issue has concluded, PoshCode#24, so lets include the agreed upon examples inside the docs :)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests