cleancode.in

Clean code in Go

Go leaves layout to gofmt: tabs, and no line length limit. Names are MixedCaps, never underscores, and a capital first letter makes a name visible outside its package.

What does Effective Go ask for?

  • With Go we take an unusual approach and let the machine take care of most formatting issues. source

From Effective Go.

How should Go code look?

  • gofmt writes every Go program in one standard layout. source
  • Tabs for indentation. source
  • No line length limit. source

What else does it ask?

  • An upper case first letter makes a name visible outside its package. source
  • Package names: lower case, one word. source
  • A getter is called Owner, not GetOwner. source
  • Handle each error and return early; no else needed. source

How are names written in Go?

KindExampleRule
TypesShoppingCartMixedCaps, no underscores. source
FunctionsaddItemMixedCaps, no underscores. source
VariablesitemCountMixedCaps, no underscores. source
ConstantsmaxItemsMixedCaps, no underscores. source

What does cleaner Go look like?

Before
func (s *store) Get_owner() string { return s.owner }

func load_config(path string) (*Config, error) {
	f, err := os.Open(path)
	if err == nil {
		defer f.Close()
		return parse(f)
	} else {
		return nil, err
	}
}
After
func (s *store) Owner() string { return s.owner }

func loadConfig(path string) (*Config, error) {
	f, err := os.Open(path)
	if err != nil {
		return nil, err
	}
	defer f.Close()
	return parse(f)
}

What changed?

  • The getter is Owner, not Get_owner. source
  • mixedCaps in place of underscores: loadConfig. source
  • The error is handled first and returns; no else. source
  • Tabs, as gofmt writes them. source