blob: 49c23449b273afdd4ded1b03e1c5fbdb7c945471 [file] [log] [blame] [view]
Andrew Gerrand5bc444d2014-12-10 11:35:11 +11001(TODO: Add table of contents.)
2
3# Go Code Review Comments
4
5This page collects common comments made during reviews of Go code, so
6that a single detailed explanation can be referred to by shorthands.
7This is a laundry list of common mistakes, not a style guide.
8
9You can view this as a supplement to http://golang.org/doc/effective_go.html.
10
11**Please discuss changes before editing this page**, even _minor_ ones. Many people have opinions and this is not the place for edit wars.
12
13## gofmt
14
15Run [gofmt](http://golang.org/cmd/gofmt/) on your code to automatically fix the majority of mechanical style issues. Almost all Go code in the wild uses ` gofmt `. The rest of this document addresses non-mechanical style points.
16
17An alternative is to use [goimports](https://godoc.org/code.google.com/p/go.tools/cmd/goimports), a superset of ` gofmt ` which additionally adds (and removes) import lines as necessary.
18
19## Comment Sentences
20
21See http://golang.org/doc/effective_go.html#commentary. Comments documenting declarations should be full sentences, even if that seems a little redundant. This approach makes them format well when extracted into godoc documentation. Comments should begin with the name of the thing being described and end in a period:
22
23```
24// A Request represents a request to run a command.
25type Request struct { ...
26
27// Encode writes the JSON encoding of req to w.
28func Encode(w io.Writer, req *Request) { ...
29```
30
31and so on.
32
33## Doc Comments
34
35All top-level, exported names should have doc comments, as should non-trivial unexported type or function declarations. See http://golang.org/doc/effective_go.html#commentary for more information about commentary conventions.
36
37## Don't Panic
38
39See http://golang.org/doc/effective_go.html#errors. Don't use panic for normal error handling. Use error and multiple return values.
40
41## Error Strings
42
43Error strings should not be capitalized (unless beginning with proper nouns or acronyms) or end with punctuation, since they are usually printed following other context. That is, use fmt.Errorf("something bad") not fmt.Errorf("Something bad"), so that log.Print("Reading %s: %v", filename, err) formats without a spurious capital letter mid-message. This does not apply to logging, which is implicitly line-oriented and not combined inside other messages.
44
45## Handle Errors
46
47See http://golang.org/doc/effective_go.html#errors. Do not discard errors using ` _ ` variables. If a function returns an error, check it to make sure the function succeeded. Handle the error, return it, or, in truly exceptional situations, panic.
48
49## Imports
50
51Imports are organized in groups, with blank lines between them. The standard library packages are in the first group.
52
53```
54package main
55
56import (
57 "fmt"
58 "hash/adler32"
59 "os"
60
61 "appengine/user"
62 "appengine/foo"
63
64 "code.google.com/p/x/y"
65 "github.com/foo/bar"
66)
67```
68
69<a href='https://godoc.org/code.google.com/p/go.tools/cmd/goimports'>goimports</a> will do this for you.
70
71## Import Dot
72
73The import . form can be useful in tests that, due to circular dependencies, cannot be made part of the package being tested:
74
75```
76package foo_test
77
78import (
79 . "foo"
80 "bar/testutil" // also imports "foo"
81)
82```
83
84In this case, the test file cannot be in package foo because it uses bar/testutil, which imports foo. So we use the 'import .' form to let the file pretend to be part of package foo even though it is not. Except for this one case, do not use import . in your programs. It makes the programs much harder to read because it is unclear whether a name like Quux is a top-level identifier in the current package or in an imported package.
85
86## Indent Error Flow
87
88Try to keep the normal code path at a minimal indentation, and indent the error handling, dealing with it first. This improves the readability of the code by permitting visually scanning the normal path quickly. For instance, don't write
89
90```
91if err != nil {
92 // error handling
93} else {
94 // normal code
95}
96```
97
98Instead, write
99
100```
101if err != nil {
102 // error handling
103 return // or continue, etc.
104}
105// normal code
106```
107
108If the if statement has an initialization statement that, such as
109
110```
111if x, err := f(); err != nil {
112 // error handling
113 return
114} else {
115 // use x
116}
117```
118
119then this may require moving the short variable declaration to its own line:
120
121```
122x, err := f()
123if err != nil {
124 // error handling
125 return
126}
127// use x
128```
129
130## Initialisms
131
132Words in names that are initialisms or acronyms (e.g. "URL" or "NATO") have a consistent case. For example, "URL" should appear as "URL" or "url" (as in "urlPony", or "URLPony"), never as "Url". Here's an example: ServeHTTP not ServeHttp.
133
134This rule also applies to "ID" when it is short for "identifier," so write "appID" instead of "appId".
135
136Code generated by the protocol buffer compiler is exempt from this rule. Human-written code is held to a higher standard than machine-written code.
137
138## Line Length
139
140There is no rigid line length limit in Go code, but avoid uncomfortably long lines. Similarly, don't add line breaks to keep lines short when they are more readable long--for example, if they are repetitive.
141
142Comments are typically wrapped before no more than 80 characters, not because it's a rule, but because it's more readable when viewing in an editor that might be sized to show hundreds of columns wide. Humans are better at following narrow text (e.g. columns in a newspaper) than giant walls of wide text, as a wide editor might show. Regardless, godoc should render it nicely either way.
143
144## Mixed Caps
145
146See http://golang.org/doc/effective_go.html#mixed-caps. This applies even when it breaks conventions in other languages. For example an unexported constant is ` maxLength ` not ` MaxLength ` or ` MAX_LENGTH `.
147
148## Named Result Parameters
149
150Consider what it will look like in godoc. Named result parameters like:
151
152```
153func (n *Node) Parent1() (node *Node)
154func (n *Node) Parent2() (node *Node, err error)
155```
156will stutter in godoc; better to use:
157```
158func (n *Node) Parent1() *Node
159func (n *Node) Parent2() (*Node, error)
160```
161
162On the other hand, if a function returns two or three parameters of the same type, or if the meaning of a result isn't clear from context, adding names may be useful. For example:
163
164```go
165
166func (f *Foo) Location() (float64, float64, error)```
167is less clear than
168```go
169
170// Location returns f's latitude and longitude.
171// Negative values mean south and west, respectively.
172func (f *Foo) Location() (lat, long float64, err error)```
173
174Naked returns are okay if the function is a handful of lines. Once it's a medium-sized function, be explicit with your return values. Corollary: it's not worth it to name result parameters just because it enables you to use naked returns. Clarity of docs is always more important than saving a line or two in your function.
175
176Finally, in some cases you need to name a result parameter in order to change it in a deferred closure. That is always okay.
177
178## Naked Returns
179
180See [CodeReviewComments#Named\_Result\_Parameters](wiki/CodeReviewComments#Named_Result_Parameters).
181
182## Package Comments
183
184Package comments, like all comments to be presented by godoc, must appear adjacent to the package clause, with no blank line.
185
186```
187// Package math provides basic constants and mathematical functions.
188package math
189```
190
191```
192/*
193Package template implements data-driven templates for generating textual
194output such as HTML.
195....
196*/
197package template
198```
199
200See http://golang.org/doc/effective_go.html#commentary for more information about commentary conventions.
201
202## Package Names
203
204All references to names in your package will be done using the package name, so you can omit that name from the identifiers. For example, if you are in package chubby, you don't need type ChubbyFile, which clients will write as chubby.ChubbyFile. Instead, name the type File, which clients will write as chubby.File. See http://golang.org/doc/effective_go.html#package-names for more.
205
206## Pass Values
207
208Don't pass pointers as function arguments just to save a few bytes. If a function refers to its argument ` x ` only as ` *x ` throughout, then the argument shouldn't be a pointer. Common instances of this include passing a pointer to a string (` *string `) or a pointer to an interface value (` *io.Reader `). In both cases the value itself is a fixed size and can be passed directly. This advice does not apply to large structs, or even small structs that might grow.
209
210## Receiver Names
211
212The name of a method's receiver should be a reflection of its identity; often a one or two letter abbreviation of its type suffices (such as "c" or "cl" for "Client"). Don't use generic names such as "me", "this" or "self", identifiers typical of object-oriented languages that place more emphasis on methods as opposed to functions. The name need not be as descriptive as a that of a method argument, as its role is obvious and serves no documentary purpose. It can be very short as it will appear on almost every line of every method of the type; familiarity admits brevity. Be consistent, too: if you call the receiver "c" in one method, don't call it "cl" in another.
213
214## Receiver Type
215
216Choosing whether to use a value or pointer receiver on methods can be difficult, especially to new Go programmers. If in doubt, use a pointer, but there are times when a value receiver makes sense, usually for reasons of efficiency, such as for small unchanging structs or values of basic type. Some rules of thumb:
217
218 * If the receiver is a map, func or chan, don't use a pointer to it.
219 * If the receiver is a slice and the method doesn't reslice or reallocate the slice, don't use a pointer to it.
220 * If the method needs to mutate the receiver, the receiver must be a pointer.
221 * If the receiver is a struct that contains a sync.Mutex or similar synchronizing field, the receiver must be a pointer to avoid copying.
222 * If the receiver is a large struct or array, a pointer receiver is more efficient. How large is large? Assume it's equivalent to passing all its elements as arguments to the method. If that feels too large, it's also too large for the receiver.
223 * Can function or methods, either concurrently or when called from this method, be mutating the receiver? A value type creates a copy of the receiver when the method is invoked, so outside updates will not be applied to this receiver. If changes must be visible in the original receiver, the receiver must be a pointer.
224 * If the receiver is a struct, array or slice and any of its elements is a pointer to something that might be mutating, prefer a pointer receiver, as it will make the intention more clear to the reader.
225 * If the receiver is a small array or struct that is naturally a value type (for instance, something like the time.Time type), with no mutable fields and no pointers, or is just a simple basic type such as int or string, a value receiver makes sense. A value receiver can reduce the amount of garbage that can be generated; if a value is passed to a value method, an on-stack copy can be used instead of allocating on the heap. (The compiler tries to be smart about avoiding this allocation, but it can't always succeed.) Don't choose a value receiver type for this reason without profiling first.
226 * Finally, when in doubt, use a pointer receiver.
227
228## Useful Test Failures
229
230Tests should fail with helpful messages saying what was wrong, with what inputs, what was actually got, and what was expected. It may be tempting to write a bunch of assertFoo helpers, but be sure your helpers produce useful error messages. Assume that the person debugging your failing test is not you, and is not your team. A typical Go test fails like:
231
232```
233 if got != tt.want {
234 t.Errorf("Foo(%q) = %d; want %d", tt.in, got, tt.want) // or Fatalf, if test can't test anything more past this point
235 }
236```
237
238Note that the order here is actual != expected, and the message uses that order too. Some test frameworks encourage writing these backwards: 0 != x, "expected 0, got x", and so on. Go does not.
239
240If that seems like a lot of typing, you may want to write a table-driven test: http://code.google.com/p/go-wiki/wiki/TableDrivenTests
241
242Another common technique to disambiguate failing tests when using a test helper with different input is to wrap each caller with a different TestFoo function, so the test fails with that name:
243
244```
245 func TestSingleValue(t *testing.T) { testHelper(t, []int{80}) }
246 func TestNoValues(t *testing.T) { testHelper(t, []int{}) }
247```
248
249In any case, the onus is on you to fail with a helpful message to whoever's debugging your code in the future.
250
251## Variable Names
252
253Variable names in Go should be short rather than long. This is especially true for local variables with limited scope. Prefer c to lineCount. Prefer i to sliceIndex.
254
255The basic rule: the further from its declaration that a name is used, the more descriptive the name must be. For a method receiver, one or two letters is sufficient. Common variables such as loop indices and readers can be a single letter (` i `, ` r `). More unusual things and global variables need more descriptive names.