diff --git a/src/var-scope.md b/src/var-scope.md index 362b651e..f3ae6d5f 100644 --- a/src/var-scope.md +++ b/src/var-scope.md @@ -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). @@ -66,3 +66,37 @@ return nil
+ +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. + + + + + +
BadGood
+ +```go +const ( + _defaultPort = 8080 + _defaultUser = "user" +) + +func Bar() { + fmt.Println("Default port", _defaultPort) +} +``` + + + +```go +func Bar() { + const ( + defaultPort = 8080 + defaultUser = "user" + ) + fmt.Println("Default port", defaultPort) +} +``` + +
diff --git a/style.md b/style.md index 21a1733a..71db54c1 100644 --- a/style.md +++ b/style.md @@ -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). @@ -3276,6 +3276,40 @@ return nil
+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. + + + + + +
BadGood
+ +```go +const ( + _defaultPort = 8080 + _defaultUser = "user" +) + +func Bar() { + fmt.Println("Default port", _defaultPort) +} +``` + + + +```go +func Bar() { + const ( + defaultPort = 8080 + defaultUser = "user" + ) + fmt.Println("Default port", defaultPort) +} +``` + +
+ ### Avoid Naked Parameters Naked parameters in function calls can hurt readability. Add C-style comments