1. Package contract: what exactly you promise to external code
When you write code in one file, it seems that everything is under control: "well, I know what is happening here." But as soon as a package appears, the code turns into a small library. And suddenly it turns out that your future "user" is you a month later (and already without fresh memories), your colleague, tests, and sometimes an entirely different project.
A package contract is a set of promises that the package makes to the outside world. In Go, the most direct language of the contract is the exported API: exported types, functions, methods, variables, constants. Change the contract — and you can break users. This is literally one of the basic meanings of compatibility: you cannot "just remove the API," because someone may already have relied on it.
Let's think practically: a good contract makes a package predictable. A bad contract makes a package a "box of surprises," where every attempt to "improve" the implementation risks blowing up external code.
Minimal API: export
There is a simple (and a little sad) truth: an exported name is almost impossible to take back without pain. Of course, you can declare it deprecated and keep a permanent museum in the code, but that is a separate art form.
That is why one of the most useful habits in Go is to start with a small export. The logic is simple: what is not exported can be changed every day, as long as tests pass and behavior remains the same. What is exported starts living by the rules of "we promised this."
Imagine that a package is a cafe. The exported API is the menu. If you print 80 pages of the menu every day, visitors spend time not on food, but on reading. A minimal API is a short menu, where every dish is actually ordered.
A small table that helps you "sober up"
| Element | Exported? | What it means in practice |
|---|---|---|
|
Yes/No | Outside code can create/compare/copy values and expect stability |
| Structure fields | Yes/No | Field export = external code can change it directly (invariants leak) |
|
Yes | You promise a correct creation method |
|
Yes | You promise a distinguishable error cause (it will be checked via errors.Is) |
|
Yes | You promise behavior and signature; renaming is a breaking change |
The main idea: we export not because it is "convenient right now," but because "this is really part of the contract."
2. Model invariants: why it is better to hide fields
Very often beginners (and sometimes not only beginners) do this: they create a struct, export the fields — and rejoice that "now everything is simple." But this is simplicity at the level of "I removed the door from the fridge — now it is easier to get the food out." Yes, easier. But there is a nuance: the temperature also became "more convenient," because it no longer exists.
Invariants are rules of data correctness. For example, for a task in a TODO app, it is easy to invent invariants: id must be positive, title must not be empty, done is a boolean state, not the string "yes pls".
If the fields are exported, any external code can do:
t := todo.Task{}
t.ID = -100
t.Title = ""
And that is it — your package no longer controls its own model.
Practice: make the model safe
Below is a small, but very typical pattern: hide the fields, create through a constructor, expose accessor methods.
package todo
import (
"errors"
"strings"
)
type Task struct {
id int
title string
done bool
}
func NewTask(id int, title string) (Task, error) {
title = strings.TrimSpace(title)
if id <= 0 {
return Task{}, errors.New("id must be positive")
}
if title == "" {
return Task{}, errors.New("title is empty")
}
return Task{id: id, title: title}, nil
}
Pay attention: Task{} cannot be created correctly from the outside, because the fields are not visible. But it can be created via NewTask, and there you keep the invariants.
Next, let us add methods (and yes, a short receiver is perfectly normal):
package todo
func (t Task) ID() int { return t.id }
func (t Task) Title() string { return t.title }
func (t Task) Done() bool { return t.done }
And separately a method that changes state — but now under your control:
package todo
func (t *Task) MarkDone() {
t.done = true
}
Now external code cannot "accidentally" make a task invalid by bypassing your package.
4. Errors as part of the contract: what can be promised outward
Errors in Go are values that code works with, not just text on the screen. This is an important point specifically for package contracts: once external code starts distinguishing between error causes, you are no longer just "returning a string," you are issuing a signal that can be relied upon.
"Wrap or not wrap" — an API-level decision
Here is the key idea that is very useful to remember: if you wrap an error with %w, you make the original error part of the API, because external code can write errors.Is(...) and start relying on it.
Why does this matter? Because sometimes that is correct (for example, if the source of the error was provided by the package user), and sometimes it is an implementation detail leak.
In the Go blog about errors there is a very practical example: if your package internally uses database/sql and returns sql.ErrNoRows outward through wrapping, then external code will start checking exactly sql.ErrNoRows. And then you will want to change the storage implementation — and suddenly it turns out that you cannot do that without breaking users.
So wrapping is not "prettier," but "I am exposing the internals outward."
Stable error causes for your own package
For a TODO package, we usually need external code to distinguish several causes: "not found," "validation," "internal error." Let us start with the simplest one: a sentinel error.
package todo
import "errors"
var ErrNotFound = errors.New("not found")
Now in the package code we can guarantee: if a task is not found, an error that is recognized as ErrNotFound goes outward.
An example of a function that adds context and preserves the cause:
package todo
import "fmt"
func (s *Service) Get(id int) (Task, error) {
t, err := s.store.Get(id)
if err != nil {
return Task{}, fmt.Errorf("get task %d: %w", id, err)
}
return t, nil
}
But there is an important caveat: what exactly is inside err? If s.store is an internal detail, and you do not want its errors exported outward, then %w may be unnecessary. And that is already a contract decision.
Often people do this: at the bottom (inside the package) they distinguish details, and outward they return errors of their own domain, without exposing "which exact driver/file/format it was."
5. Clear dependencies: "explicitly pass what you need"
In bad code, dependencies appear like mushrooms after rain: inside a function, a logger is suddenly created, a file is opened, current time is taken, the network is contacted, a config is read from the environment. The reader opens the function — and sees not business logic, but sorcery and side effects.
In good Go code, dependencies are tried to be made explicit. This is not about "fashionable," but about predictability. When a dependency is explicit, it is easier to understand what the behavior of the function depends on, easier to replace the dependency in tests, and easier not to hide global state.
Mini rule: a package should not decide on its own "where to get the world from"
A package should be able to work with what it was given. If it needs "now," let it be given a "clock." If it needs storage, let it be given "storage." And this does not necessarily have to immediately turn into a cosmic DI container: in Go, most of the time a constructor is enough.
Let us make a small Store interface. Here it is important not to slide into interface pollution: the interface should reflect the real needs of the service, not "everything the database can do."
package todo
type Store interface {
Get(id int) (Task, error)
Save(t Task) error
}
And clock — as a separate small contract (in Go, this is very common, because it is simple and testable):
package todo
import "time"
type Clock interface {
Now() time.Time
}
Now Service depends explicitly on Store and Clock:
package todo
type Service struct {
store Store
clock Clock
}
func NewService(store Store, clock Clock) *Service {
return &Service{store: store, clock: clock}
}
Notice: NewService is part of the package contract. You promise: the service is created like this, and the dependencies are passed like this.
Why "I will create it inside" is almost always worse
If we had done this:
func NewService() *Service {
return &Service{
store: NewPostgresStoreFromEnv(),
clock: RealClock{},
}
}
then the service would become "magical." It would depend on the environment, on a specific Postgres, on a specific way of reading configuration — and all of that would be hidden. External code does not understand why the service works exactly this way, and cannot easily replace dependencies.
And this also creates an unpleasant contract: to use the package, you must "land in the right state of the world." This usually breaks at an unexpected moment — for example, in tests or in another environment.
6. Example: a small todo app
Now let us put this together into a mini picture. We have a todo package that provides a minimal API, keeps invariants, and requires dependencies explicitly. For understanding, it is useful to see the file structure (this is not a command and not an "assignment," just a visual guide):
todo/
task.go // model + invariants
errors.go // domain error causes
service.go // use-case layer of the package
store_mem.go // internal store implementation (type may be unexported)
main.go // application assembly (in another package)
Internal in-memory store: hide the type, decide on the constructor by contract
Let us make an in-memory store. Important: the type can remain unexported if you do not want to promise it outward. At the same time, the constructor can be exported if you are ready to support it as part of the API.
Below is one variant: the type is not exported, and the constructor is exported, and we return the Store interface (this way you bind external code less tightly to a specific struct).
package todo
import "fmt"
type memStore struct {
items map[int]Task
}
func NewInMemoryStore() Store {
return &memStore{items: make(map[int]Task)}
}
func (m *memStore) Get(id int) (Task, error) {
t, ok := m.items[id]
if !ok {
return Task{}, fmt.Errorf("%w", ErrNotFound)
}
return t, nil
}
And saving:
package todo
func (m *memStore) Save(t Task) error {
m.items[t.ID()] = t
return nil
}
Here we return ErrNotFound as the cause. You can also do it without fmt.Errorf, simply return Task{}, ErrNotFound. A "blank wrap" is usually not needed, but the technique itself is useful to understand: wrapping affects the contract.
Service: a "narrow" API and clear errors
Let us add task creation through the service, where the service itself chooses the ID (yes, this is a simplification, but it is good enough for an example). Pay attention to the happy path: below.
package todo
import "fmt"
func (s *Service) Create(title string) (Task, error) {
id := int(s.clock.Now().Unix()) // the simplest example, not for production
t, err := NewTask(id, title)
if err != nil {
return Task{}, fmt.Errorf("create task: %w", err)
}
if err := s.store.Save(t); err != nil {
return Task{}, fmt.Errorf("save task: %w", err)
}
return t, nil
}
Now look through the eyes of the "package user": Create either returns a task or an error. The error carries context. External code can distinguish ErrNotFound (if that matters), but does not need to know that there is a memStore inside or which database is used.
Assembly in main: dependencies are created at the application boundary
At the application boundary we choose the dependency implementations. Inside the todo package, we do not "guess" what the world needs.
package main
import (
"fmt"
"time"
"example.com/app/todo"
)
type realClock struct{}
func (realClock) Now() time.Time { return time.Now() }
func main() {
store := todo.NewInMemoryStore()
svc := todo.NewService(store, realClock{})
t, err := svc.Create("buy milk")
if err != nil {
fmt.Println("error:", err)
return
}
fmt.Println("created:", t.Title()) // created: buy milk
}
If you do not want to promise even the NewInMemoryStore constructor outward, then that is already an application architecture-level decision: you can create memStore on the main side (for example, through an internal package or an application-level factory), and keep the todo package as domain-oriented as possible.
Compatibility and API changes: why "I'll just rename it" is not simple
Sometimes it seems: "I will rename Task.Title() to Task.Name() — and that is it." But if it is exported, then your package may already be used somewhere else. The Go team, in the context of compatibility, directly emphasizes: removing or changing exported elements breaks programs that depend on them.
A useful habit: before exporting something, ask yourself: "Am I ready to support this name and this signature for a long time?" If you are not sure — it is better not to export it.
7. Typical mistakes
Mistake #1: export struct fields "to make it convenient."
Usually this leads to invariants no longer existing, and the package starts receiving invalid data "from the outside." Then you add checks in every function, and the code turns into an obstacle course. It is much calmer to hide the fields and provide one correct creation path.
Mistake #2: turn the package into a "dumping ground" for everything.
When one package contains the model, parsing, printing, file work, and network, the contract becomes unreadable. External code does not understand "what this package actually promises." One package — one clear responsibility.
Mistake #3: hide dependencies inside the package.
If the package reads env by itself, opens files by itself, creates clients by itself — the code becomes magical. It is hard to test and hard to understand. Clear dependencies through a constructor make behavior transparent.
Mistake #4: blindly use %w at all levels.
Wrapping via %w is not just "adding context," it is a decision about the API: you allow external code to recognize the internal cause through errors.Is/errors.As. This is useful when the cause really should be visible, but harmful when you reveal implementation details (for example, a specific DB driver).
Mistake #5: expose "random strings" instead of stable causes.
If external code must distinguish "not found," "validation," "no access," then a string is a bad contract. Today the text is one thing, tomorrow another, and external logic breaks. It is better to provide stable causes (sentinel/typed errors) and translate them into messages for the user at the application boundary.
GO TO FULL VERSION