Reduce Scope of Variables
Where possible, reduce scope of variables. Do not reduce the scope if itconflicts with Reduce Nesting.
Bad | Good |
---|
- err := ioutil.WriteFile(name, data, 0644)
- if err != nil {
- return err
- }
|
- if err := ioutil.WriteFile(name, data, 0644); err != nil {
- return err
- }
|
If you need a result of a function call outside of the if, then you should nottry to reduce the scope.
Bad | Good |
---|
- if data, err := ioutil.ReadFile(name); err == nil {
- err = cfg.Decode(data)
- if err != nil {
- return err
- }
-
- fmt.Println(cfg)
- return nil
- } else {
- return err
- }
|
- data, err := ioutil.ReadFile(name)
- if err != nil {
- return err
- }
-
- if err := cfg.Decode(data); err != nil {
- return err
- }
-
- fmt.Println(cfg)
- return nil
|