uber-go / guide

The Uber Go Style Guide.
Apache License 2.0
15.91k stars 1.72k forks source link

Add more guidance on scope for constants #216

Closed tyler-french closed 3 months ago

tyler-french commented 3 months ago

Hoping to get some opinions on this.

One pattern I see a lot is with making global constants for values that are only used within a certain function.

For example

const _defaultPort = 8000

func something() {
  doSomething(_defaultPort)
  port := _defaultPort
}

In my opinion, there should be an adjustment to the # Reduce Scope of Variables section to include more emphasis on what to do with Constants.

I mostly want to get opinions here, but I generally would prefer to change the above code to the following:

func something() {
  const defaultPort = 8000
  doSomething(defaultPort)
  port := defaultPort
}

Thoughts?

tyler-french commented 3 months ago

Maybe a follow-up, what about things like types and enums:

func doSomething(input string) {
    type x string
    const (
        y x = "0"
        z x = "1"
    )
    ...
sywhang commented 3 months ago

https://github.com/uber-go/guide/blob/master/style.md#reduce-scope-of-variables kind of covers this, IMO. Perhaps adding some more examples with types/consts can be helpful?