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 1, 2024
1 parent 27820cf commit 3fb83e1
Showing 1 changed file with 35 additions and 2 deletions.
37 changes: 35 additions & 2 deletions src/var-scope.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Reduce Scope of Variables
# Reduce Scope of Variables and Constants

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>

Avoid making constants global unless they are used in multiple functions.

<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 3fb83e1

Please sign in to comment.