Q:
How to writing Beautiful Packages in Go?
A:
Motivation
- Do you have the right motivation for writing a package?
- Don’t write packages for the sake of it
- Are you excited to write it or does it sound boring?
- If you aren’t solving a problem you have, don’t bother
Keep packages internal to start with
- Don’t automatically open-source your packages
- Live with them first internally
- But design them as if you will use one day
What is a package / library ?
- Folder full of
.go
(and hopefully_test.go
) files - Can be imported into other projects
- Has exported (public) and unexported (internal) stuff
- Hopefully open-sourced
- Not
package main
(that’s a command)
What is a beautiful package?
- Elegant & simple
- Obvious (maybe even boring)
- You already know how to use it
- Look forward to using it
Structure your code properly
Subfolders
cmd
- for commandspkg
- for package codetestdata
- for, you guessed it, test datainternal
- for internal stuff that only your code will importdocs
- additional documentation- Be sensible
Keep types close to where they’re used
Organise by responsibility (
User
tpe goes intousers.go
)Optimize for
godoc
and provide examples & usegodoc
early:godoc -http=:8080
How can we make our packages beautiful?
- User centred design: Personas, Scenarios, Use cases
- Ask yourself…
- Who is the user of the package?
- What are they trying to do?
- Why are they doing it?
- Why are they using your package?
- Are they building a PoC? Or is this part of a bigger system?
- Narrow types are simpler (be more abstract more you close user).
- Try and keep interface as tiny as possible if you need it (easy to implement).
- Context as the first argument
- Don’t log stuff out
- Don’t mess with the global state
- Don’t add flags
- Avoid
init
- Don’t mess with things in the standard library (e.g. changing
http.Defaultclient
to set a timeout) - Importing your package shouldn’t have side-effects
- Leave concurrency to the user
- Test driven development
- Make zero values useful
- Avoid constructors if you can
- Use smaller APIs instead of interface
- Follow conventions
- Let computer help you
- go lint
- go vet
- github.com/golangci/golangci-lint
- goreportcard.com
Come up with a good name
- Short
- Clear
- To the point
- Be creative, and have fun
- Not every Go project needs to mention Go
Give your project a logo ormascot
- Projects that have a logo, are 85% more likely to get used
- Great way for artists to contribute to open-source projects