Skip to content

Commit 8c11368

Browse files
committed
Resolve merge conflicts and consolidate approved edits
1 parent 09ec193 commit 8c11368

File tree

1 file changed

+79
-65
lines changed

1 file changed

+79
-65
lines changed

Style-Guide/Code-Layout-and-Formatting.md

Lines changed: 79 additions & 65 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,13 @@
22

33
These guidelines are about readability. Some of them are arbitrary rules, but they are based on decades of traditions in programming, so while you may disagree with some rules (and should always follow the rules of individual projects), when we ask you to leave an empty line after a closing function brace, or two lines before functions, we're not being capricious, we're doing so because it makes it easier for experienced developers to scan your code.
44

5-
#### Maintain consistency in layout
5+
#### Maintain Consistency in Layout
66

77
Rules about indentation, line length, and capitalization are about consistency across code bases. Long practice has shown that it's easier to read and understand code when it looks familiar and you're not being distracted by details, which means that it's better for everyone in the community to follow a single set of rules.
88

99
We don't expect everyone to follow these guidelines, and rules for individual projects always trump these. Whether for legacy reasons, or to match guidelines for multiple languages in a single project, different projects may have different style guidelines. Since the goal is consistency, you should always abide by any style rules that are in place on the project you are contributing to.
1010

11-
If you do have a legacy project that is in source control and you decide to reformat code to adopt these rules, try to make all of your whitespace changes in a single commit that does _nothing_ but edit the whitespace. You should never reformat the whitespace on a file as _part_ of a content change because it makes the changes hard to spot.
11+
If you do have a legacy project that is in source control and you decide to reformat code to adopt these rules, try to make all of your whitespace changes in a single a commit that does _nothing_ but edit the whitespace. You should never reformat the whitespace on a file as _part_ of a content change because it makes the changes hard to spot.
1212

1313
#### Capitalization Conventions
1414

@@ -25,7 +25,7 @@ PowerShell uses PascalCase for _all_ public identifiers: module names, function
2525

2626
PowerShell language keywords are written in lower case (yes, even `foreach` and `dynamicparam`), as well as operators such as `-eq` and `-match`. The keywords in comment-based help are written in UPPERCASE to make it easy to spot them among the dense prose of documentation.
2727

28-
```posh
28+
```powershell
2929
function Write-Host {
3030
<#
3131
.SYNOPSIS
@@ -55,8 +55,7 @@ function Write-Host {
5555
[System.ConsoleColor]
5656
$BackgroundColor
5757
)
58-
begin
59-
{
58+
begin {
6059
...
6160
```
6261

@@ -68,92 +67,101 @@ A special case is made for two-letter acronyms in which both letters are capital
6867
6968
If you wish, you may use camelCase for variables within your functions (or modules) to distinguish _private_ variables from parameters, but this is a matter of taste. Shared variables should be distinguished by using their scope name, such as `$Script:PSBoundParameters` or `$Global:DebugPreference`. If you are using camelCase for a variable that starts with a two-letter acronym (where both letters are capitalized), both letters should be set to lowercase (such as `adComputer`).
7069

70+
#### Open braces on the same line
7171

72-
#### Always Start With CmdletBinding
73-
74-
All of your scripts or functions should start life as something like this snippet:
72+
This can be considered a matter of consistency; several common cmdlets in PowerShell take script blocks as _parameters_ (e.g., `ForEach-Object`), and in these cases it is functionally impossible to place the opening brace on a new line _without_ use of a line-continuator (i.e., ``` ` ```, a backtick), which should generally be avoided.
7573

74+
```powershell
75+
$Data | ForEach-Object {
76+
$_.Item -as [int]
77+
}
7678
```
77-
[CmdletBinding()]param()
78-
process{}
79-
end{}
79+
80+
v.s.
81+
82+
```powershell
83+
foreach ($Entry in $Data)
84+
{
85+
$Entry.Item -as [int]
86+
}
8087
```
8188

82-
You can always delete or ignore one of the blocks (or add the `begin` block), add parameters and so on, but you should avoid writing scripts or functions without CmdletBinding, and you should always at least _consider_ making it take pipeline input.
89+
As such, both native keywords and function parameters should include opening braces on the _same_ line.
8390

84-
#### Brace yourself: Follow the one-true-brace style.
85-
Open braces always go on the same line.
91+
Code folding is also nicer in many editors.
8692

87-
This style really won in the PowerShell community partly because the style is one of two used in C languages --it's a variant of the K&R (Kernighan and Ritchie) style from their book The C Programming Language-- but also because for the first few years of PowerShell's existence, this was the only style that could be typed at the command line.
93+
#### Closing Braces Always on Their Own Line
8894

89-
Code folding is nicer in many editors when a scriptblock is placed on the end of the same line, as in this example.
95+
Once again, this makes code-folding much more sensible in many editors.
9096

91-
````
92-
function Get-Noun {
93-
end {
94-
if ($Wide) {
95-
Get-Command | Sort-Object Noun -Unique | Format-Wide Noun
96-
} else {
97-
Get-Command | Sort-Object Noun -Unique | Select-Object -Expand Noun
98-
}
99-
}
100-
}
101-
````
102-
#### Closing braces start a new line
103-
Note the above example again, community guidelines recommend following the ['One-True-Brace-Style'](https://www.wikiwand.com/en/Indentation_style#/K&R_style) placing your closing braces on their own line. This practice makes it easier to pair up matching opening and closing braces when looking to see where a particular scriptblock ends, and allows one to insert new lines of code between any two lines.
97+
The exception to this rule may be in cases where the script block is a parameter, and further parameters must still be added. However, in the interests of improving code-folding, readability, and maintainability, placing such parameters _before_ the script block parameter should be considered, where possible.
10498

105-
To reiterate, these are community best practices, and a lot of the code you'll find online from community leaders will follow these guidelines. That doesn't mean that those who follow different style guidelines are wrong. You may be the one to set the course for your company or your own project; we simply offer this guidance for your consideration.
99+
#### Always Start With CmdletBinding
106100

107-
#### Prefer: param() begin, process, end
108-
That's the order PowerShell will execute it in
109-
(TODO)
101+
All of your scripts or functions should start life as something like this snippet:
110102

103+
```powershell
104+
[CmdletBinding()]
105+
param()
106+
process {}
107+
end {}
108+
```
111109

112-
#### Indentation
110+
You can always delete or ignore one of the blocks (or add the `begin` block), add parameters and necessary valiation and so on, but you should **avoid** writing scripts or functions without `[CmdletBinding()]`, and you should always at least _consider_ making it take pipeline input.
113111

114-
##### Use four *spaces* per indentation level.
112+
#### Prefer: param(), begin, process, end
115113

116-
This is what PowerShell ISE does and understands, and it's the default for most code editors. As always, existing projects may have different standards, but for public code, please stick to 4 spaces, and the rest of us will try to do the same.
114+
Having a script written in the order of execution makes its intent more clear. There is no functional purpose to having `begin` be declared _after_ `process`. Although it _will_ still be executed in the correct order, writing in such a fashion significantly detracts from the readability of a script.
117115

118-
The 4-space rule is optional for continuation lines. Hanging indents (when indenting a wrapped command which was too long) may be indented more than one indentation level, or may even be indented an odd number of spaces to line up with a method call or parameter block.
116+
As a general rule, unreadable scripts are also difficult to maintain or debug.
119117

120-
```PowerShell
118+
#### Indentation
121119

122-
# This is ok
123-
$MyObj.GetData(
124-
$Param1,
125-
$Param2,
126-
$Param3,
127-
$Param4
128-
)
120+
##### Use four *spaces* per indentation level
129121

130-
# This is better
131-
$MyObj.GetData($Param1,
132-
$Param2,
133-
$Param3,
134-
$Param4)
122+
Usually you use the `[Tab]` key to indent, but most editors can be configured to insert spaces instead of actual tab characters when you indent. For most programming languages and editors (including PowerShell ISE) the default is four spaces, and that's what we recommend. Different teams and projects may have different standards, and you should abide by them in the interest of maintaining consistency of style in a given project.
123+
124+
```powershell
125+
function Test-Code {
126+
foreach ($exponent in 1..10) {
127+
[Math]::Pow(2, $exponent)
128+
}
129+
}
135130
```
136131

132+
Indenting more than 4-spaces is acceptable for continuation lines (when you're wrapping a line which was too long). In such cases you might indent more than one level, or even indent indent an odd number of spaces to line up with a method call or parameter block on the line before.
133+
134+
```powershell
135+
function Test-Code {
136+
foreach ($base in 1,2,4,8,16) {
137+
foreach ($exponent in 1..10) {
138+
[System.Math]::Pow($base,
139+
$exponent)
140+
}
141+
}
142+
```
137143

138144
#### Maximum Line Length
139145

140146
Limit lines to 115 characters when possible.
141147

142148
The PowerShell console is, by default, 120 characters wide, but it allows only 119 characters on output lines, and when entering multi-line text, PowerShell uses a line continuation prompt: `>>> ` and thus limits your line length to 116 anyway.
143149

150+
Additionally, keeping lines to a set width allows scripts to be read in _one_ direction (top to bottom) with no horizontal scrolling required. For many, having to scroll in both directions detracts from a smooth reading and comprehension of the script.
151+
144152
Most of us work on widescreen monitors these days, and there is little reason to keep a narrow line width, however, keeping files relatively narrow allows for side-by-side editing, so even narrower guidelines may be established by a given project. Be sure to check when you're working on someone else's project.
145153

146-
The preferred way to avoid long lines is to use splatting (see [About Splatting](https://technet.microsoft.com/en-us/library/jj672955.aspx)) and PowerShell's implied line continuation inside parentheses, brackets, and braces -- these should always be used in preference to the backtick for line continuation when applicable, even for strings:
154+
The preferred way to avoid long lines is to use splatting (see [Get-Help about_Splatting](https://technet.microsoft.com/en-us/library/jj672955.aspx)) and PowerShell's implied line continuation inside parentheses, brackets, and braces -- these should **always** be used in preference to the backtick for line continuation when applicable, even for strings:
147155

148-
```
156+
```powershell
149157
Write-Host ("This is an incredibly important, and extremely long message. " +
150158
"We cannot afford to leave any part of it out, nor do we want line-breaks in the output. " +
151-
"Using string concatenation let's us use short lines here, and still get a long line in the output")
159+
"Using string concatenation lets us use short lines here, and still get a long line in the output")
152160
```
153161

154-
#### Blank lines
162+
#### Blank Lines and Whitespace
155163

156-
Surround function and class definitions with two blank lines.
164+
Surround function and class definitions with _two_ blank lines.
157165

158166
Method definitions within a class are surrounded by a single blank line.
159167

@@ -171,7 +179,7 @@ Lines should not have trailing whitespace. Extra spaces result in future edits w
171179

172180
You should use a single space around parameter names and operators, including comparison operators and math and assignment operators, even when the spaces are not necessary for PowerShell to correctly parse the code.
173181

174-
A notable exception is when using colons to pass values to switch parameters:
182+
One notable exception is when using colons to pass values to switch parameters:
175183

176184
```PowerShell
177185
# Do not write:
@@ -202,28 +210,34 @@ $yesterdaysDate = (Get-Date).AddDays(-$i)
202210

203211
#### Spaces around special characters
204212

205-
White-space is (mostly) irrelevant to PowerShell, but its proper use is the key to writing easily readable code.
213+
White-space is (mostly) irrelevant to PowerShell, but its proper use is key to writing easily readable code.
206214

207215
Use a single space after commas and semicolons, and around pairs of curly braces.
208216

209-
Avoid extra spaces inside parenthesis or square braces.
217+
Avoid unnecessary extra spaces inside parenthesis or square braces.
218+
219+
Subexpressions `$( ... )` and script blocks `{ ... }` should have a single space _inside_ the enclosing braces or parentheses to make code stand out and be more readable.
210220

211-
Nested expressions `$( ... )` and script blocks `{ ... }` should have a single space _inside_ them to make code stand out and be more readable.
221+
Subexpressions `$( ... )` and variable delimiters `${...}` nested inside strings should not include additional space _surrounding_ them, unless it is desired for the final string to include them.
212222

213-
Nested expressions `$( ... )` and variable delimiters `${...}` inside strings do not need spaces _outside_, since that would become a part of the string.
223+
```powershell
224+
$Var = 1
225+
"This is a string with one (${Var}) delimited variable."
214226
227+
"This is $( 2 - 1 ) string with $( 1 + 1 ) numbers contained within."
228+
```
215229

216-
#### Avoid using semicolons (`;`) at the end of each line.
230+
#### Avoid Using Semicolons (`;`) as Line Terminators
217231

218-
PowerShell will not complain about extra semicolons, but they are unnecessary, and get in the way when code is being edited or copy-pasted. They also result in extra do-nothing edits in source control when someone finally decides to delete them.
232+
PowerShell will not complain about extra semicolons, but they are unnecessary, and can get in the way when code is being edited or copy-pasted. They also result in extra do-nothing edits in source control when someone finally decides to delete them.
219233

220234
They are also unecessary when declaring hashtables if you are already putting each element on it's own line:
221235

222236
```PowerShell
223-
# This is the preferred way to declare a hashtable if it must go past one line:
237+
# This is the preferred way to declare a hashtable if it extends past one line:
224238
$Options = @{
225-
Margin = 2
226-
Padding = 2
239+
Margin = 2
240+
Padding = 2
227241
FontSize = 24
228242
}
229243
```

0 commit comments

Comments
 (0)