Skip to content

Commit

Permalink
give guidance to reduce scope of constants
Browse files Browse the repository at this point in the history
  • Loading branch information
tyler-french committed Aug 9, 2024
1 parent 27820cf commit c036a5a
Showing 1 changed file with 34 additions and 1 deletion.
35 changes: 34 additions & 1 deletion src/var-scope.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Reduce Scope of Variables

Where possible, reduce scope of variables. Do not reduce the scope if it
Where possible, reduce scope of variables and constants. Do not reduce the scope if it
conflicts with [Reduce Nesting](nest-less.md).

<table>
Expand Down Expand Up @@ -66,3 +66,36 @@ return nil

</td></tr>
</tbody></table>

Constants do not need to be global unless they are used in multiple functions or files.

<table>
<thead><tr><th>Bad</th><th>Good</th></tr></thead>
<tbody>
<tr><td>

```go
const (
_defaultPort = 8080
_defaultUser = "user"
)

func Bar() {
fmt.Println("Default port", _defaultPort)
}
```

</td><td>

```go
func Bar() {
const (
defaultPort = 8080
defaultUser = "user"
)
fmt.Println("Default port", _defaultPort)
}
```

</td></tr>
</tbody></table>

0 comments on commit c036a5a

Please sign in to comment.