Skip to content

Commit

Permalink
give guidance to reduce scope of constants (#217)
Browse files Browse the repository at this point in the history
* give guidance to reduce scope of constants

* Auto-update style.md

* Update var-scope.md

Co-authored-by: Abhinav Gupta <[email protected]>

* Update var-scope.md

Co-authored-by: Abhinav Gupta <[email protected]>

* Auto-update style.md

---------

Co-authored-by: tyler-french <[email protected]>
Co-authored-by: Abhinav Gupta <[email protected]>
  • Loading branch information
3 people authored Aug 9, 2024
1 parent 27820cf commit a66b53b
Show file tree
Hide file tree
Showing 2 changed files with 70 additions and 2 deletions.
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

0 comments on commit a66b53b

Please sign in to comment.