This is a second post of a series that started here based on a talk I gave about Go and Clean Code(slides here, in Portuguese)

Now I’m gonna talk about package names and how to choose package names in the Go way.

First of all, packages in Go is how Go code is organized. It is similar to a Python module and pretty much the same as a Java package, a C# namespace or a JavaScript component. It is a folder containing code that, in a good software architecture, has something in common.

The guidelines provided by Effective Go on naming packages are pretty good - the bottom line is that you should:

  1. Keep ‘em short and concise (and don’t worry about name collisions).
  2. Choose a name good enough to give context to your exported Interfaces, Structs and Function.

The first one is for readability. Name collisions hardly happens, and when they do, the importer of the package can make a decision and change the reference of the imported package. It’s not up to a package to avoid name collisions, but to its importers.

199
import mylogger "log"

The second one is kinda tricky, but when you see the implementation of the Reader interface across packages, it’s easier to see the point:

199
200
201
202
203
204
205
import "io"
import "bufio"
import "bytes"

var reader *io.Reader
var bufreader *bufio.Reader
var bytesreader *bytes.Reader

In all of the three cases, the type is Reader and the package name is short, concise enough and it gives context to the content of the package.

When Go’s standard library gained an implementation of a Ring data structure, it gained a package named ring. Initializing a new ring was just a matter of calling ring.New(). This is normally how you should write your constructors.

199
200
import "ring"
ring := ring.New()

Good package names are very important to writing a code that’s nice and easy to read. I also believe this blog post regarding package names is a great resource!

So, that pretty much sums up what I what to say. I strongly recommend reading the references!

Cool reference links

Past Posts