Skip to content

Latest commit

 

History

History
102 lines (80 loc) · 1.48 KB

var-scope.md

File metadata and controls

102 lines (80 loc) · 1.48 KB

Reduce Scope of Variables

Where possible, reduce scope of variables and constants. Do not reduce the scope if it conflicts with Reduce Nesting.

BadGood
err := os.WriteFile(name, data, 0644)
if err != nil {
 return err
}
if err := os.WriteFile(name, data, 0644); err != nil {
 return err
}

If you need a result of a function call outside of the if, then you should not try to reduce the scope.

BadGood
if data, err := os.ReadFile(name); err == nil {
  err = cfg.Decode(data)
  if err != nil {
    return err
  }

  fmt.Println(cfg)
  return nil
} else {
  return err
}
data, err := os.ReadFile(name)
if err != nil {
   return err
}

if err := cfg.Decode(data); err != nil {
  return err
}

fmt.Println(cfg)
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
const (
  _defaultPort = 8080
  _defaultUser = "user"
)

func Bar() {
  fmt.Println("Default port", _defaultPort)
}
func Bar() {
  const (
    defaultPort = 8080
    defaultUser = "user"
  )
  fmt.Println("Default port", defaultPort)
}