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
Copy file name to clipboardExpand all lines: Style-Guide/Code-Layout-and-Formatting.md
+79-65Lines changed: 79 additions & 65 deletions
Original file line number
Diff line number
Diff line change
@@ -2,13 +2,13 @@
2
2
3
3
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.
4
4
5
-
#### Maintain consistency in layout
5
+
#### Maintain Consistency in Layout
6
6
7
7
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.
8
8
9
9
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.
10
10
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.
12
12
13
13
#### Capitalization Conventions
14
14
@@ -25,7 +25,7 @@ PowerShell uses PascalCase for _all_ public identifiers: module names, function
25
25
26
26
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.
27
27
28
-
```posh
28
+
```powershell
29
29
function Write-Host {
30
30
<#
31
31
.SYNOPSIS
@@ -55,8 +55,7 @@ function Write-Host {
55
55
[System.ConsoleColor]
56
56
$BackgroundColor
57
57
)
58
-
begin
59
-
{
58
+
begin {
60
59
...
61
60
```
62
61
@@ -68,92 +67,101 @@ A special case is made for two-letter acronyms in which both letters are capital
68
67
69
68
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`).
70
69
70
+
#### Open braces on the same line
71
71
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.
75
73
74
+
```powershell
75
+
$Data | ForEach-Object {
76
+
$_.Item -as [int]
77
+
}
76
78
```
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
+
}
80
87
```
81
88
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.
83
90
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.
86
92
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
88
94
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.
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.
104
98
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
106
100
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:
110
102
103
+
```powershell
104
+
[CmdletBinding()]
105
+
param()
106
+
process {}
107
+
end {}
108
+
```
111
109
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.
113
111
114
-
##### Use four *spaces* per indentation level.
112
+
####Prefer: param(), begin, process, end
115
113
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.
117
115
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.
119
117
120
-
```PowerShell
118
+
#### Indentation
121
119
122
-
# This is ok
123
-
$MyObj.GetData(
124
-
$Param1,
125
-
$Param2,
126
-
$Param3,
127
-
$Param4
128
-
)
120
+
##### Use four *spaces* per indentation level
129
121
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
+
}
135
130
```
136
131
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
+
```
137
143
138
144
#### Maximum Line Length
139
145
140
146
Limit lines to 115 characters when possible.
141
147
142
148
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.
143
149
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
+
144
152
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.
145
153
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:
147
155
148
-
```
156
+
```powershell
149
157
Write-Host ("This is an incredibly important, and extremely long message. " +
150
158
"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")
152
160
```
153
161
154
-
#### Blank lines
162
+
#### Blank Lines and Whitespace
155
163
156
-
Surround function and class definitions with two blank lines.
164
+
Surround function and class definitions with _two_ blank lines.
157
165
158
166
Method definitions within a class are surrounded by a single blank line.
159
167
@@ -171,7 +179,7 @@ Lines should not have trailing whitespace. Extra spaces result in future edits w
171
179
172
180
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.
173
181
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:
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.
206
214
207
215
Use a single space after commas and semicolons, and around pairs of curly braces.
208
216
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.
210
220
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.
212
222
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."
214
226
227
+
"This is $( 2 - 1 ) string with $( 1 + 1 ) numbers contained within."
228
+
```
215
229
216
-
#### Avoid using semicolons (`;`) at the end of each line.
230
+
#### Avoid Using Semicolons (`;`) as Line Terminators
217
231
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.
219
233
220
234
They are also unecessary when declaring hashtables if you are already putting each element on it's own line:
221
235
222
236
```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:
0 commit comments