Upgrade to Pro — share decks privately, control downloads, hide ads and more …

The Boring Programmer: Best Practices in Go

The Boring Programmer: Best Practices in Go

Go has made me the boring programmer, writing only strict and rigid code. If you don't like that, think of it as pragmatic and safe. This talk shares practices about how to write Go code and explains where some of the philosophical decision originate from and decisively make Go the language it is today.

Konrad Reiche

May 17, 2018
Tweet

More Decks by Konrad Reiche

Other Decks in Technology

Transcript

  1. Packages Packages should contain code that has a single purpose.

    Group of packages that provide the same set of functionalities should be organized under the same parent. The choices of your package have a huge impact on the testability.
  2. github.com/simplaex/lighthouse ├── cmd/ │ └──lighthouse/ │ ├── subcmd/ │ └──

    lighthouse.go ├── internal/ │ ├── api/ │ ├── datastore/ │ ├── model/ │ ├── registrations/ │ └── platform/ | └── vendor/ ├── github.com/ │ ├── golang/ │ ├── go-kit/ └── golang.org/ All programs go under cmd. Each subdirectory has a matching source code file containing the main package Packages under internal can be imported within the project, but not from outside Model packages for your domain entities. Datastore package to implement your database queries. Dependencies go under vendor.
  3. Dep dep is a prototype dependency management tool for Go.

    dep is safe for production use. dep is the official experiment, but not yet the official tool. $ dep ensure $ dep ensure -add github.com/foo/bar $ ls Gopkg.toml Gopkg.lock
  4. CI Setup Use gometalinter github.com/alecthomas/gometalinter. Over 30 tools for statically

    checking Go source for errors and warnings. Not only about nit-picking, actually points towards potential sources of bugs. Always test with -race. Especially with you integration tests, try to perform your actions concurrently to uncover data races. Data races crash your program.
  5. CGO

  6. CGO - Cgo must always be guarded with build tags

    // +build linux,386 darwin,!cgo - Context switches are very expensive - You assume Cgo will be fast - But calls to C are actually atrocious expensive - Treat it like a microservice
  7. Clear is better than Clever - Go code should be

    straight up boring - If you look at it, you should understand what it’s doing - You don’t put explanations into the comment - Being overly clever will hurt you in the long-run - The boring programmer writes strict and rigid code - That’s why Go is great for production-grade code