CodeGym /コース /Go SELF /Package contracts — minimal API

Package contracts — minimal API

Go SELF
レベル 37, レッスン 4
使用可能

1. Package contract: what exactly do you promise to external code

One file of code can feel fully under control: “well, I know what is happening here.” But once 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 no longer with fresh memory), your colleague, your tests, and sometimes even another project.

A package contract is the set of promises 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 depend on it.

Let us 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 codebase, but that is already a separate kind of art.

That is why one of the most useful habits in Go is to start with a small export. The logic is this: what is not exported can be changed every day as long as the tests pass and behavior stays 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 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 table that helps you “sober up”

Element Exported? What it means in practice
type Task struct { ... }
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 out)
func NewX(...) X
Yes You promise a correct way to create it
var ErrSomething
Yes You promise a distinguishable error cause (it will be checked via errors.Is)
func (x X) Method()
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 structure, export the fields — and are happy that “now everything is simple”. But that is simplicity at the level of “I removed the door from the fridge — now it is easier to take out the food”. Yes, easier. But there is a nuance: the temperature also became “easier”, because it no longer exists.

Invariants are the rules of data correctness. For example, for 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 fields are exported, any external code can do this:

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 fields, create through a constructor, and expose access 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
}

Notice: Task{} cannot be correctly created from the outside, because the fields are not visible. But it can be created through NewTask, and there you preserve the invariants.

Next, 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 the task invalid while bypassing your package.

4. Errors as part of the contract: what you can promise outward

In Go, errors are values that code works with, not just text on the screen. This matters a lot for package contracts: once external code starts distinguishing error causes, you are no longer just “returning a string”, you are issuing a signal that others can rely on.

“Wrap or not wrap” — an API-level decision

Here is the key idea worth remembering: if you wrap an error with %w, you make the original error part of the API, because external code will be able to write errors.Is(...) and start depending on it.

Why does this matter? Because sometimes that is correct (for example, if the error source was given by the package user), and sometimes it leaks implementation details.

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, external code will begin 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 “opening internals to the outside”.

Stable error causes for your own package

For a TODO package, we usually want external code to distinguish several causes: “not found”, “validation”, “internal error”. Let us start with the simplest thing: a sentinel error.

package todo

import "errors"

var ErrNotFound = errors.New("not found")

Now in package code we can guarantee: if a task is not found, an error that is recognized as ErrNotFound goes outward.

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 here 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 the pattern is this: down below (inside the package) you distinguish details, and outward you return errors of your own domain, without revealing “which exact driver/file/format it was”.

5. Clear dependencies: “pass explicitly 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 called, 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 made explicit. This is not about being “modern”, but about predictability. When a dependency is explicit, it is easier to understand what the function behavior depends on, easier to replace dependencies in tests, and easier not to hide global state.

Mini rule: the package should not decide where to “take the world from”

A package should know how to work with what it is given. If it needs “now”, let it be given “clock”. If it needs storage, let it be given “storage”. And this does not have to turn into a space-age DI container right away: in Go, a constructor is usually 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 (Go people really like doing this, 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 that the service is created this way, and dependencies are passed this way.

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 would not understand why the service works exactly this way, and could not easily replace dependencies.

And this also creates an unpleasant contract: to use the package, you have to “land in the correct state of the world”. That usually breaks at the most unexpected moment — for example, in tests or in another environment.

6. Example: a small todo app

Now let us assemble this into a mini picture. We have a package todo that provides a minimal API, preserves invariants, and requires dependencies explicitly. For understanding, it is useful to see the file structure (this is not a command or 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 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 option: the type is not exported, and the constructor is exported and returns the Store interface (this ties external code less to a concrete structure).

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 unnecessary, 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 chooses the ID itself (yes, this is just a simplification, but it works for the example). Notice the happy path: at the bottom.

package todo

import "fmt"

func (s *Service) Create(title string) (Task, error) {
	id := int(s.clock.Now().Unix()) // 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 from the package user’s point of view: 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 what is inside memStore or which database is used.

Assembly in main: dependencies are created at the application boundary

At the application boundary we choose the implementation of dependencies. 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("牛乳を買う")
	if err != nil {
		fmt.Println("error:", err)
		return
	}
	fmt.Println("created:", t.Title()) // created: 牛乳を買う
}

If you do not want to promise even the NewInMemoryStore constructor outward, then that is already an application-architecture 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-focused as possible.

Compatibility and API changes: why “I’ll just rename it” is not just that

Sometimes it feels like: “I will rename Task.Title() to Task.Name() — and that is all.” But if it is exported, your package may already be used somewhere else. The Go team, in the context of compatibility, explicitly 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 unsure, it is better not to export it.

7. Typical mistakes

Mistake #1: exporting structure fields “for convenience”.
Usually this leads to invariants no longer existing, and the package starts receiving invalid data from the outside. Then you add checks to every function, and the code turns into an obstacle course. It is much calmer to hide fields and provide one correct creation path.

Mistake #2: turning a package into a dump for everything.
When a package contains model, parsing, printing, file work, and networking all together, the contract becomes unreadable. External code has no idea “what this package even promises”. One package — one clear responsibility.

Mistake #3: hiding 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 using %w at all levels.
Wrapping with %w is not just “adding context”, it is an API decision: you allow external code to recognize the internal cause via errors.Is/errors.As. That is useful when the cause really should be visible, but harmful when you expose implementation details (for example, a specific database driver).

Mistake #5: exposing “random strings” instead of stable causes.
If external code must distinguish “not found”, “validation”, “access denied”, then a string is a poor contract. Today the text is one thing, tomorrow another, and external logic breaks. Better to provide stable causes (sentinel/typed errors) and translate them into user-facing messages at the application boundary.

1
タスク
Go SELF, レベル 37, レッスン 4
ロック未解除
挨拶パッケージ
挨拶パッケージ
1
タスク
Go SELF, レベル 37, レッスン 4
ロック未解除
アカウントのユーザー
アカウントのユーザー
1
タスク
Go SELF, レベル 37, レッスン 4
ロック未解除
商品カタログ
商品カタログ
1
タスク
Go SELF, レベル 37, レッスン 4
ロック未解除
メモサービス
メモサービス
1
アンケート/クイズ
Go におけるクリーンコード、レベル 37、レッスン 4
使用不可
Go におけるクリーンコード
Go におけるクリーンコード
コメント
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION