Illustration: pixabay

The beginning of writing a good Go package is to come up with a good name. Think of your bag name as an elevator pitch, and you must explain it with one word.

A common reason for bad package names is that they’re called Utility. These packages mix helpers with utility code, and contain a variety of unrelated functions that can be difficult to describe based on what they provide. This often results in a package whose name depends on what it contains: utilities.

Package names like utils and helpers are commonly used to avoid circular references and reuse helper functions when developing projects with deep package structures. Extracting generic methods into a new package breaks circular references, but since the package was created because of a project design problem, its name does not reflect its purpose, only its ability to break circular references.

[A little] duplication is far cheaper than the wrong abstraction.

– Sandy Metz

To improve the package name of utils or helpers, my recommended method is to analyze where the package is referenced, and then move the related function into the calling package. Even if this leads to some code redundancy, it’s better than introducing dependencies between the two packages. In this case, where utility package functions are used in multiple places, I prefer to split them into multiple packages and use descriptive names.

When common functionality exists in two or more related toolkits, it is common to find packages with names like Base or Common. For example, public types between a client and a server, or between a server and its mocks, are refactored into separate packages. Instead, the solution is to reduce the number of packages by combining client, Server, and common code into a single package named for the functionality it provides.

For example, net/ HTTP packages do not have client and server packages. Instead, they contain client.go and server.go files, each with its own type, The transport.go file contains the public message transfer code used on the HTTP clients and Servers side.

Name a package after what it provides, not what it contains.

The posts

  1. Simple profiling package moved, updated

  2. The package level logger anti pattern

  3. How to include C code in your Go package

  4. Why I think Go package management is important


via: https://dave.cheney.net/2019/01/08/avoid-package-names-like-base-util-or-common

By Dave Cheney

This article is originally compiled by GCTT and published by Go Chinese