Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

give guidance to reduce scope of constants #217

Merged
merged 5 commits into from
Aug 9, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 35 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,37 @@ return nil

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

Constants do not need to be global unless they are used in multiple functions or files
or are part of an external contract of the package.

<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>
36 changes: 35 additions & 1 deletion style.md
Original file line number Diff line number Diff line change
Expand Up @@ -3209,7 +3209,7 @@ be treated differently in different situations (such as serialization).

### 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](#reduce-nesting).

<table>
Expand Down Expand Up @@ -3276,6 +3276,40 @@ return nil
</td></tr>
</tbody></table>

Constants do not need to be global unless they are used in multiple functions or files
or are part of an external contract of the package.

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

### Avoid Naked Parameters

Naked parameters in function calls can hurt readability. Add C-style comments
Expand Down