|
| 1 | +# Common Mistakes |
| 2 | + |
| 3 | +## Resource Leaks |
| 4 | + |
| 5 | +### 1. Missing defer for Close |
| 6 | + |
| 7 | +**Problem**: Resources leaked on early return. |
| 8 | + |
| 9 | +```go |
| 10 | +// BAD |
| 11 | +func readFile(path string) ([]byte, error) { |
| 12 | + f, err := os.Open(path) |
| 13 | + if err != nil { |
| 14 | + return nil, err |
| 15 | + } |
| 16 | + data, err := io.ReadAll(f) |
| 17 | + if err != nil { |
| 18 | + return nil, err // file never closed! |
| 19 | + } |
| 20 | + f.Close() |
| 21 | + return data, nil |
| 22 | +} |
| 23 | + |
| 24 | +// GOOD - defer immediately |
| 25 | +func readFile(path string) ([]byte, error) { |
| 26 | + f, err := os.Open(path) |
| 27 | + if err != nil { |
| 28 | + return nil, err |
| 29 | + } |
| 30 | + defer f.Close() |
| 31 | + return io.ReadAll(f) |
| 32 | +} |
| 33 | +``` |
| 34 | + |
| 35 | +### 2. Defer in Loop |
| 36 | + |
| 37 | +**Problem**: Resources accumulate until function returns. |
| 38 | + |
| 39 | +```go |
| 40 | +// BAD - files stay open until loop ends |
| 41 | +for _, path := range paths { |
| 42 | + f, _ := os.Open(path) |
| 43 | + defer f.Close() // deferred until function returns |
| 44 | + process(f) |
| 45 | +} |
| 46 | + |
| 47 | +// GOOD - close in each iteration or use closure |
| 48 | +for _, path := range paths { |
| 49 | + func() { |
| 50 | + f, _ := os.Open(path) |
| 51 | + defer f.Close() |
| 52 | + process(f) |
| 53 | + }() |
| 54 | +} |
| 55 | +``` |
| 56 | + |
| 57 | +### 3. HTTP Response Body Not Closed |
| 58 | + |
| 59 | +**Problem**: Connection pool exhaustion. |
| 60 | + |
| 61 | +```go |
| 62 | +// BAD |
| 63 | +resp, err := http.Get(url) |
| 64 | +if err != nil { |
| 65 | + return err |
| 66 | +} |
| 67 | +// body never closed! |
| 68 | +data, _ := io.ReadAll(resp.Body) |
| 69 | + |
| 70 | +// GOOD |
| 71 | +resp, err := http.Get(url) |
| 72 | +if err != nil { |
| 73 | + return err |
| 74 | +} |
| 75 | +defer resp.Body.Close() |
| 76 | +data, _ := io.ReadAll(resp.Body) |
| 77 | +``` |
| 78 | + |
| 79 | +## Naming and Style |
| 80 | + |
| 81 | +### 4. Stuttering Names |
| 82 | + |
| 83 | +**Problem**: Redundant when used with package name. |
| 84 | + |
| 85 | +```go |
| 86 | +// BAD |
| 87 | +package user |
| 88 | +type UserService struct { ... } // user.UserService |
| 89 | + |
| 90 | +// GOOD |
| 91 | +package user |
| 92 | +type Service struct { ... } // user.Service |
| 93 | +``` |
| 94 | + |
| 95 | +### 5. Missing Doc Comments on Exports |
| 96 | + |
| 97 | +**Problem**: godoc can't generate documentation. |
| 98 | + |
| 99 | +```go |
| 100 | +// BAD |
| 101 | +func NewServer(addr string) *Server { ... } |
| 102 | + |
| 103 | +// GOOD |
| 104 | +// NewServer creates a new HTTP server listening on addr. |
| 105 | +func NewServer(addr string) *Server { ... } |
| 106 | +``` |
| 107 | + |
| 108 | +### 6. Naked Returns in Long Functions |
| 109 | + |
| 110 | +**Problem**: Hard to track what's being returned. |
| 111 | + |
| 112 | +```go |
| 113 | +// BAD |
| 114 | +func process(data []byte) (result string, err error) { |
| 115 | + // 50 lines of code... |
| 116 | + |
| 117 | + return // what's being returned? |
| 118 | +} |
| 119 | + |
| 120 | +// GOOD - explicit returns |
| 121 | +func process(data []byte) (string, error) { |
| 122 | + // 50 lines of code... |
| 123 | + |
| 124 | + return processedString, nil |
| 125 | +} |
| 126 | +``` |
| 127 | + |
| 128 | +## Initialization |
| 129 | + |
| 130 | +### 7. Init Function Overuse |
| 131 | + |
| 132 | +**Problem**: Hidden side effects, hard to test. |
| 133 | + |
| 134 | +```go |
| 135 | +// BAD - global state via init |
| 136 | +var db *sql.DB |
| 137 | + |
| 138 | +func init() { |
| 139 | + var err error |
| 140 | + db, err = sql.Open("postgres", os.Getenv("DATABASE_URL")) |
| 141 | + if err != nil { |
| 142 | + log.Fatal(err) |
| 143 | + } |
| 144 | +} |
| 145 | + |
| 146 | +// GOOD - explicit initialization |
| 147 | +type App struct { |
| 148 | + db *sql.DB |
| 149 | +} |
| 150 | + |
| 151 | +func NewApp(dbURL string) (*App, error) { |
| 152 | + db, err := sql.Open("postgres", dbURL) |
| 153 | + if err != nil { |
| 154 | + return nil, fmt.Errorf("opening db: %w", err) |
| 155 | + } |
| 156 | + return &App{db: db}, nil |
| 157 | +} |
| 158 | +``` |
| 159 | + |
| 160 | +### 8. Global Mutable State |
| 161 | + |
| 162 | +**Problem**: Race conditions, hard to test. |
| 163 | + |
| 164 | +```go |
| 165 | +// BAD |
| 166 | +var config Config |
| 167 | + |
| 168 | +func GetConfig() Config { |
| 169 | + return config |
| 170 | +} |
| 171 | + |
| 172 | +// GOOD - dependency injection |
| 173 | +type Server struct { |
| 174 | + config Config |
| 175 | +} |
| 176 | + |
| 177 | +func NewServer(cfg Config) *Server { |
| 178 | + return &Server{config: cfg} |
| 179 | +} |
| 180 | +``` |
| 181 | + |
| 182 | +## Performance |
| 183 | + |
| 184 | +### 9. String Concatenation in Loop |
| 185 | + |
| 186 | +**Problem**: O(n²) allocation overhead. |
| 187 | + |
| 188 | +```go |
| 189 | +// BAD |
| 190 | +var result string |
| 191 | +for _, s := range items { |
| 192 | + result += s + ", " |
| 193 | +} |
| 194 | + |
| 195 | +// GOOD |
| 196 | +var b strings.Builder |
| 197 | +for _, s := range items { |
| 198 | + b.WriteString(s) |
| 199 | + b.WriteString(", ") |
| 200 | +} |
| 201 | +result := b.String() |
| 202 | +``` |
| 203 | + |
| 204 | +### 10. Slice Preallocation |
| 205 | + |
| 206 | +**Problem**: Repeated reallocations. |
| 207 | + |
| 208 | +```go |
| 209 | +// BAD - grows dynamically |
| 210 | +var results []Result |
| 211 | +for _, item := range items { |
| 212 | + results = append(results, process(item)) |
| 213 | +} |
| 214 | + |
| 215 | +// GOOD - preallocate known size |
| 216 | +results := make([]Result, 0, len(items)) |
| 217 | +for _, item := range items { |
| 218 | + results = append(results, process(item)) |
| 219 | +} |
| 220 | +``` |
| 221 | + |
| 222 | +## Testing |
| 223 | + |
| 224 | +### 11. Table-Driven Tests Missing |
| 225 | + |
| 226 | +**Problem**: Verbose, repetitive test code. |
| 227 | + |
| 228 | +```go |
| 229 | +// BAD |
| 230 | +func TestAdd(t *testing.T) { |
| 231 | + if Add(1, 2) != 3 { |
| 232 | + t.Error("1+2 should be 3") |
| 233 | + } |
| 234 | + if Add(0, 0) != 0 { |
| 235 | + t.Error("0+0 should be 0") |
| 236 | + } |
| 237 | +} |
| 238 | + |
| 239 | +// GOOD |
| 240 | +func TestAdd(t *testing.T) { |
| 241 | + tests := []struct { |
| 242 | + a, b, want int |
| 243 | + }{ |
| 244 | + {1, 2, 3}, |
| 245 | + {0, 0, 0}, |
| 246 | + {-1, 1, 0}, |
| 247 | + } |
| 248 | + for _, tt := range tests { |
| 249 | + got := Add(tt.a, tt.b) |
| 250 | + if got != tt.want { |
| 251 | + t.Errorf("Add(%d, %d) = %d, want %d", tt.a, tt.b, got, tt.want) |
| 252 | + } |
| 253 | + } |
| 254 | +} |
| 255 | +``` |
| 256 | + |
| 257 | +## Review Questions |
| 258 | + |
| 259 | +1. Is `defer Close()` called immediately after opening resources? |
| 260 | +2. Are HTTP response bodies always closed? |
| 261 | +3. Are package-level names not stuttering with package name? |
| 262 | +4. Do exported symbols have doc comments? |
| 263 | +5. Is mutable global state avoided? |
| 264 | +6. Are slices preallocated when size is known? |
0 commit comments