Reduce Scope of Variables

Where possible, reduce scope of variables. Do not reduce the scope if itconflicts with Reduce Nesting.

BadGood
  1. err := ioutil.WriteFile(name, data, 0644)
  2. if err != nil {
  3. return err
  4. }
  1. if err := ioutil.WriteFile(name, data, 0644); err != nil {
  2. return err
  3. }

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

BadGood
  1. if data, err := ioutil.ReadFile(name); err == nil {
  2. err = cfg.Decode(data)
  3. if err != nil {
  4. return err
  5. }
  6.  
  7. fmt.Println(cfg)
  8. return nil
  9. } else {
  10. return err
  11. }
  1. data, err := ioutil.ReadFile(name)
  2. if err != nil {
  3. return err
  4. }
  5.  
  6. if err := cfg.Decode(data); err != nil {
  7. return err
  8. }
  9.  
  10. fmt.Println(cfg)
  11. return nil