Learn Go with AI · Free online book
Chapter 5: Organizing Code: Packages and Interfaces
In short: Chapter 5 splits Tracker into packages and introduces interfaces, with one Storage interface that has a file version and an in-memory version for tests. The behavior doesn't change, so your tests make the refactor safe, and the AI starts implementing code to your rules.
Look at Tracker’s folder. Formatting money, storing expenses, reading the command line and printing the report all live in package main. It works, but it’s getting crowded, and a crowded package is hard to read, for you and for the AI. When everything can touch everything, every change is risky.
In this chapter, you’ll split Tracker into packages: one for money, one for expenses. You’ll decide what each package shows to the outside world with exported names. And you’ll give Tracker an interface for storage, so the same code can save to a file in real use and keep everything in memory during tests.
The AI’s role changes twice in this chapter. First it’s your pair: you do the reorganizing, and it reviews. Then, for the first time, it’s the implementer: you write the tests, the AI writes the code, and you review it. It’s the same SURE loop, but by the end of this chapter the AI is typing and you’re the one deciding whether its work is good enough.
Mission
By the end of this chapter, you’ll have:
- A
moneypackage that formats amounts, and aledgerpackage that records and stores expenses - A
Storageinterface, with a file version for the program and a memory version for tests - One set of tests that every kind of storage must pass
- Your expenses kept out of Git with a
.gitignorefile - Two commits: one for your reorganization, one for the AI’s code
Tracker’s behavior won’t change at all. Every command from Chapter 4 prints exactly what it did before. Changing how code is organized without changing what it does is called refactoring, and your tests are what make it safe.
Must know
- A package is a folder. Every
.gofile in a folder starts with the samepackageline. Other code imports it by your module’s name plus the folder:"tracker/ledger". - A capital first letter means exported.
money.Formatcan be used from other packages;money.splitCentscan’t. The rule is the same for functions, types, methods and struct fields. - Name things for how they read from outside. Callers write
money.Format(350)andledger.Open(...), so don’t repeat the package name:money.FormatMoneysays “money” twice. - An interface is a list of methods. Any type that has all those methods satisfies the interface automatically. Go has no
implementskeyword. - Pointer receivers count. If a type’s methods have pointer receivers, like
(m *MemoryStorage), then only the pointer,&MemoryStorage{}, satisfies the interface.
Specify
Add these sentences to SPEC.md, after the existing five:
6. Every command in sentences 1-5 works exactly as before.
7. Package money formats amounts. Package ledger records expenses
and saves them through a Storage interface.
8. Storage has two versions: a JSON file, used by the program,
and memory, used in tests. Both pass the same storage tests.
9. expenses.json is not tracked by Git.
Sentence 6 is the most important one. A refactor that changes behavior isn’t a refactor; it’s a bug.
Write the tests first
Make the two package folders, from the tracker folder:
mkdir money
mkdir ledger
In money, create money_test.go. It’s your old TestFormatAmount, moved and renamed:
package money
import "testing"
func TestFormat(t *testing.T) {
tests := []struct {
cents int
want string
}{
{350, "3.50"},
{1200, "12.00"},
{99, "0.99"},
{5, "0.05"},
{0, "0.00"},
}
for _, tt := range tests {
got := Format(tt.cents)
if got != tt.want {
t.Errorf("Format(%d) = %q, want %q", tt.cents, got, tt.want)
}
}
}
The first line says package money, not package main. A test file belongs to the package in its folder.
In ledger, create ledger_test.go. The first two tests come from tracker_test.go. The third is new: it opens a Tracker, adds an expense, saves it, then opens a second Tracker on the same storage to check the expense is still there.
package ledger
import (
"errors"
"maps"
"testing"
)
func TestTrackerAdd(t *testing.T) {
tests := []struct {
name string
category string
cents int
wantErr error
wantLen int
}{
{"valid", "Food", 350, nil, 1},
{"zero", "Food", 0, ErrInvalidAmount, 0},
{"negative", "Food", -100, ErrInvalidAmount, 0},
}
for _, tt := range tests {
var tr Tracker
err := tr.Add(tt.category, tt.cents)
if !errors.Is(err, tt.wantErr) {
t.Errorf("%s: Add() error = %v, want %v", tt.name, err, tt.wantErr)
}
if len(tr.expenses) != tt.wantLen {
t.Errorf("%s: %d expenses after Add, want %d", tt.name, len(tr.expenses), tt.wantLen)
}
}
}
func TestTrackerTotals(t *testing.T) {
tr := Tracker{expenses: []Expense{
{Category: "Food", Cents: 350},
{Category: "Transport", Cents: 1200},
{Category: "Food", Cents: 99},
}}
got := tr.Totals()
want := map[string]int{"Food": 449, "Transport": 1200}
if !maps.Equal(got, want) {
t.Errorf("Totals() = %v, want %v", got, want)
}
}
func TestOpenAddSave(t *testing.T) {
store := &MemoryStorage{}
first, err := Open(store)
if err != nil {
t.Fatalf("Open() error = %v", err)
}
if err := first.Add("Food", 350); err != nil {
t.Fatalf("Add() error = %v", err)
}
if err := first.Save(); err != nil {
t.Fatalf("Save() error = %v", err)
}
second, err := Open(store)
if err != nil {
t.Fatalf("Open() again error = %v", err)
}
got := second.Totals()
want := map[string]int{"Food": 350}
if !maps.Equal(got, want) {
t.Errorf("Totals() after reopening = %v, want %v", got, want)
}
}
TestOpenAddSave uses MemoryStorage, so it never touches the disk. That’s the first payoff of an interface: Tracker doesn’t care where its expenses go.
Also in ledger, create storage_test.go. This is the heart of the chapter:
package ledger
import (
"os"
"path/filepath"
"slices"
"testing"
)
// testStorage checks the rules every Storage must follow.
func testStorage(t *testing.T, store Storage) {
t.Helper()
saved := []Expense{
{Category: "Food", Cents: 350},
{Category: "Fun", Cents: 1500},
}
if err := store.Save(saved); err != nil {
t.Fatalf("Save() error = %v", err)
}
saved[0].Cents = 1 // Changing our slice must not change what was saved.
got, err := store.Load()
if err != nil {
t.Fatalf("Load() error = %v", err)
}
want := []Expense{
{Category: "Food", Cents: 350},
{Category: "Fun", Cents: 1500},
}
if !slices.Equal(got, want) {
t.Errorf("Load() = %v, want %v", got, want)
}
}
func TestFileStorage(t *testing.T) {
path := filepath.Join(t.TempDir(), "expenses.json")
testStorage(t, FileStorage{Path: path})
}
func TestFileStorageMissingFile(t *testing.T) {
path := filepath.Join(t.TempDir(), "missing.json")
store := FileStorage{Path: path}
got, err := store.Load()
if err != nil {
t.Fatalf("Load() error = %v, want nil", err)
}
if len(got) != 0 {
t.Errorf("Load() returned %d expenses, want 0", len(got))
}
}
func TestFileStorageBrokenFile(t *testing.T) {
path := filepath.Join(t.TempDir(), "expenses.json")
if err := os.WriteFile(path, []byte("not json"), 0o644); err != nil {
t.Fatal(err)
}
store := FileStorage{Path: path}
if _, err := store.Load(); err == nil {
t.Error("Load() error = nil, want an error for a broken file")
}
}
func TestMemoryStorage(t *testing.T) {
testStorage(t, &MemoryStorage{})
}
testStorage isn’t a test by itself; its name doesn’t start with Test. It’s a helper that takes any Storage and checks the rules every storage must follow. TestFileStorage and TestMemoryStorage each run it on one kind of storage. Write the rules once, check every version.
Look at the line saved[0].Cents = 1. After saving, the test changes its own slice, and then checks that the storage still returns the original amounts. A file naturally keeps its own copy. The memory version must do the same on purpose, and this line checks that it does.
t.Helper() tells Go that this is a helper, so when it fails, Go reports the line in the test that called it, not a line inside the helper.
Run the tests:
go test ./...
ok tracker (cached)
# tracker/money [tracker/money.test]
money/money_test.go:17:10: undefined: Format
# tracker/ledger [tracker/ledger.test]
ledger/storage_test.go:11:38: undefined: Storage
ledger/storage_test.go:14:13: undefined: Expense
ledger/ledger_test.go:18:23: undefined: ErrInvalidAmount
ledger/ledger_test.go:19:30: undefined: ErrInvalidAmount
ledger/ledger_test.go:22:10: undefined: Tracker
ledger/ledger_test.go:34:8: undefined: Tracker
ledger/ledger_test.go:34:28: undefined: Expense
ledger/ledger_test.go:47:12: undefined: MemoryStorage
ledger/ledger_test.go:49:16: undefined: Open
ledger/ledger_test.go:60:17: undefined: Open
ledger/storage_test.go:14:13: too many errors
FAIL tracker/ledger [build failed]
FAIL tracker/money [build failed]
FAIL
go test ./... now tests three packages: tracker (your main package, still passing), tracker/ledger and tracker/money. tracker hasn’t changed since Chapter 4, so Go reuses its last result and prints (cached). Go builds packages in parallel, so the money and ledger error blocks may appear in the other order for you.
Use the AI: pair
You’ll do the reorganizing yourself, one package at a time. After each step, compare your file with the book’s listing.
The money package
Create money/money.go. Move formatAmount and splitCents into it from main.go, rename formatAmount to Format (capital F, so other packages can use it), and add comments. It should look like this:
// Package money formats amounts stored as whole cents.
package money
import "fmt"
// Format returns an amount in cents as text, like "3.50".
func Format(cents int) string {
whole, rest := splitCents(cents)
return fmt.Sprintf("%d.%02d", whole, rest)
}
func splitCents(cents int) (int, int) {
return cents / 100, cents % 100
}
splitCents stays lowercase. Nothing outside money needs it, so it stays private, and you can change it later without breaking anyone.
A comment that starts with the name it describes, like // Format returns..., is a doc comment. Go’s tools show it to anyone who uses the package.
The ledger package
Create ledger/ledger.go. Move Expense, ErrInvalidAmount, Tracker, Add and Totals into it from tracker.go. Two things change:
Trackergets a second field,store Storage, so it knows where its expenses are saved.- Instead of
Load(path), there’sOpen(store), which loads expenses from anyStorage.Saveloses itspathparameter, because the Tracker already knows its store.
// Package ledger records expenses and totals them by category.
package ledger
import (
"errors"
"fmt"
)
// Expense is one thing you spent money on.
type Expense struct {
Category string `json:"category"`
Cents int `json:"cents"`
}
// ErrInvalidAmount means an expense amount was zero or negative.
var ErrInvalidAmount = errors.New("amount must be more than zero")
// Tracker holds all your expenses and the storage they live in.
type Tracker struct {
store Storage
expenses []Expense
}
// Open loads the expenses from store into a new Tracker.
func Open(store Storage) (*Tracker, error) {
expenses, err := store.Load()
if err != nil {
return nil, err
}
return &Tracker{store: store, expenses: expenses}, nil
}
// Add records one expense.
func (tr *Tracker) Add(category string, cents int) error {
if cents <= 0 {
return fmt.Errorf("add %q: %w", category, ErrInvalidAmount)
}
tr.expenses = append(tr.expenses, Expense{Category: category, Cents: cents})
return nil
}
// Totals returns the total in cents for each category.
func (tr *Tracker) Totals() map[string]int {
totals := make(map[string]int)
for _, e := range tr.expenses {
totals[e.Category] += e.Cents
}
return totals
}
// Save writes all expenses to the Tracker's storage.
func (tr *Tracker) Save() error {
return tr.store.Save(tr.expenses)
}
Now create ledger/storage.go, with the Storage interface and the file version. FileStorage’s two methods are your old Load and Save, reshaped to fit the interface:
package ledger
import (
"encoding/json"
"errors"
"fmt"
"os"
)
// Storage saves and loads expenses.
type Storage interface {
Load() ([]Expense, error)
Save(expenses []Expense) error
}
// FileStorage keeps expenses in a JSON file.
type FileStorage struct {
Path string
}
// Load reads expenses from the file. A missing file means no expenses yet.
func (s FileStorage) Load() ([]Expense, error) {
data, err := os.ReadFile(s.Path)
if errors.Is(err, os.ErrNotExist) {
return nil, nil
}
if err != nil {
return nil, fmt.Errorf("load expenses: %w", err)
}
var expenses []Expense
if err := json.Unmarshal(data, &expenses); err != nil {
return nil, fmt.Errorf("load expenses: %w", err)
}
return expenses, nil
}
// Save writes expenses to the file as JSON.
func (s FileStorage) Save(expenses []Expense) error {
data, err := json.MarshalIndent(expenses, "", " ")
if err != nil {
return fmt.Errorf("save expenses: %w", err)
}
if err := os.WriteFile(s.Path, data, 0o644); err != nil {
return fmt.Errorf("save expenses: %w", err)
}
return nil
}
The interface says what storage can do: Load and Save. FileStorage says how. Nowhere does FileStorage mention Storage. It has both methods, so it satisfies the interface, and that’s all Go needs.
FileStorage’s methods use a value receiver, (s FileStorage), because they never change s. They only read s.Path.
Connect main, and tidy up
main now uses the new packages, so the old code goes:
- Delete
tracker.goandtracker_test.go. Their code now lives inledger. - In
main.go, deleteformatAmountandsplitCents(now inmoney) andtotal. - In
main_test.go, deleteTestFormatAmount(nowTestFormatinmoney) andTestTotal.
Why delete total? Since Chapter 4, Tracker.Totals does the adding, so total is only called by its own test. Code that only its test uses is dead code: it costs reading time and does nothing. Git remembers it if you ever want it back.
Then make three small changes in main.go. Replace the import block:
import (
"errors"
"fmt"
"os"
"slices"
"strconv"
"tracker/ledger"
"tracker/money"
)
The blank line separates the standard library from your own packages. gofmt keeps each group sorted.
In run, open the Tracker with file storage, and save without a path:
tracker, err := ledger.Open(ledger.FileStorage{Path: dataFile})
if err := tracker.Save(); err != nil {
And in formatExpense, use the money package:
return name + ": " + money.Format(cents)
Now check sentence 6: nothing should have changed. Your expenses.json from Chapter 4 is still there, so run:
go run .
Welcome to Tracker. Let's see where your money goes.
Food: 4.49
Fun: 15.00
Transport: 12.00
Same as before. Then run the tests:
go test ./...
# tracker/ledger [tracker/ledger.test]
ledger/ledger_test.go:47:12: undefined: MemoryStorage
ledger/storage_test.go:65:18: undefined: MemoryStorage
ok tracker 0.002s
FAIL tracker/ledger [build failed]
ok tracker/money 0.001s
FAIL
One thing left: MemoryStorage. That’s the AI’s job, in a moment.
Ask for a review
Review how I split Tracker into the money and ledger packages:
package names, exported names, doc comments and the Storage
interface. List problems and suggestions with a one-line reason
each. Don't rewrite my code; I'll decide what to change.
Use the same three questions: Do I understand it? Does it fit this project? Do the tests still pass? Here are example suggestions (not real AI output) and how they sort:
| Suggestion | Keep? | Why |
|---|---|---|
Rename ledger to models or utils |
Reject | Vague names say nothing about what’s inside. ledger says what it is. |
Export Tracker.expenses so main can read it |
Reject | main only needs Totals. Keeping the slice private means only Add can change it, and Add checks the amount. |
Wrap the error in Open: fmt.Errorf("open tracker: %w", err) |
Your call | More context in messages. The storage errors already say “load expenses,” so it’s optional. |
Add a DatabaseStorage for the future |
Skip | Nothing needs it yet. An interface with two real versions is enough. |
Keep personal data out of Git
Since storage moved, now’s the time to fix something from Chapter 4: expenses.json is in Git. Your expenses are made up, but real ones are personal. And once something is committed, it stays in your project’s history even after you delete the file. If you ever push the project online, everyone can read that history. The safest data is data that never enters Git.
Create a file named .gitignore in the tracker folder with one line:
expenses.json
Make sure the file is named exactly .gitignore, with no .txt at the end. (Notepad on Windows likes to add one.) .gitignore tells Git which files to leave alone. But it only affects files Git isn’t already tracking, and Git has tracked expenses.json since Chapter 4. So tell Git to stop, without deleting your file:
git rm --cached expenses.json
rm 'expenses.json'
--cached means “remove it from Git, but keep it on disk.” Your expenses are still there; run go run . to check.
Commit your part
Commit before the AI starts, so its changes are easy to see on their own. The ledger tests don’t build yet; that’s expected, because MemoryStorage is the AI’s job next.
git add .
git commit -m "Split Tracker into money and ledger packages" -m "Learned: a capital first letter exports a name from its package; lowercase keeps it private."
Use the AI: implementer
Now the AI writes code, for the first time in this book. You’ve already done the most important part: the tests in storage_test.go say exactly what MemoryStorage must do. Ask:
Implement MemoryStorage in ledger/storage.go so that
go test ./... passes. It keeps expenses in memory and must satisfy
the Storage interface. Use only the standard library. Don't change
any test files.
The last sentence matters. An AI asked to make tests pass can be tempted to change the tests.
Review the AI’s work
As the implementer’s reviewer, check in this order:
Did it touch only what you asked?
git status --shortM ledger/storage.goOne changed file. If a test file appears here, the AI changed your tests. Undo that with
git restoreand the file’s name, and ask again.Let Go check.
gofmt -l .andgo vet ./...print nothing, andgo test ./...printsokthree times.Read the change.
git diffshows exactly which lines the AI added. Read every one. Can you explain each line? Why does it need a pointer receiver? How does it keep its own copy?
Here’s one version that passes. The AI’s may look different:
// MemoryStorage keeps expenses in memory. Nothing is written to disk.
type MemoryStorage struct {
expenses []Expense
}
// Load returns a copy of the saved expenses.
func (m *MemoryStorage) Load() ([]Expense, error) {
return slices.Clone(m.expenses), nil
}
// Save keeps a copy of expenses.
func (m *MemoryStorage) Save(expenses []Expense) error {
m.expenses = slices.Clone(expenses)
return nil
}
This version also adds "slices" to the imports in storage.go. Save needs a pointer receiver because it changes m.expenses; that’s Chapter 4’s lesson again. slices.Clone makes a copy, so changing the caller’s slice can’t change what was saved. That’s what the saved[0].Cents = 1 line in your test checks.
When you understand every line, run everything one last time:
go test ./...
ok tracker 0.002s
ok tracker/ledger 0.003s
ok tracker/money 0.001s
Review
Let Go check first
gofmt -l .
go vet ./...
go test ./...
Break it on purpose
Break 1: use a private name. In main.go, change money.Format(cents) to money.splitCents(cents) and run go build .:
# tracker
./main.go:65:29: undefined: money.splitCents
Your line number may differ. From outside its package, a lowercase name doesn’t exist. Change it back.
Break 2: forget the copy. In MemoryStorage, change Load to return m.expenses, nil and Save to m.expenses = expenses, then remove "slices" from the imports. Run go test ./...:
ok tracker 0.002s
--- FAIL: TestMemoryStorage (0.00s)
storage_test.go:65: Load() = [{Food 1} {Fun 1500}], want [{Food 350} {Fun 1500}]
FAIL
FAIL tracker/ledger 0.003s
ok tracker/money 0.001s
FAIL
Without the copy, the storage and the test share one slice, so the test’s change after saving leaked into the “saved” data. Notice the line number: 65 is the line in TestMemoryStorage that called testStorage, thanks to t.Helper(). Put the copies back.
Check it yourself
Be SURE you can explain it, especially the code you didn’t type.
Explain
Say it in your own words
Write a few sentences about how Tracker is organized now. For example:
Let the AI quiz you
Ask me two questions about packages, exported names or interfaces,
using my code. Wait for my answers before you tell me if I'm right.
Write a Learned: line in your commit
git add .
git commit -m "Add MemoryStorage" -m "Learned: any type with the right methods satisfies an interface, so one test can check every kind of storage."
Update AGENTS.md if something surprised you
Did the AI change a test, add an extra package, or leave out doc comments? Add a rule, then commit it.
Practice (optional)
Your AGENTS.md has grown chapter by chapter. Now test whether the AI actually follows it.
Add three rules to
AGENTS.md. For example:Every exported name gets a doc comment that starts with the name. Never edit files ending in _test.go unless I ask. Error messages start with a lowercase letter and don't end with punctuation.Specify a small feature: a
Count() intmethod onTrackerthat returns how many expenses it holds. Write its test inledger_test.gofirst, and watch it fail. Then commit your failing test before you ask the AI (git add .thengit commit -m "Add Count test"). That way, a test file ingit statusreally means the AI touched it, andgit restoreonly undoes the AI’s work.Use the AI as implementer: ask it to add
Countso the tests pass, without mentioning your rules.Review against your rules. Does
Counthave a doc comment starting withCount? Didgit statusshow only non-test files changed? If the AI broke a rule, reword the rule to be clearer, undo the change withgit restore, and ask again.
You’re done when the AI follows all three rules without being reminded. If one rule keeps failing, that tells you something too: some rules need to be checked by you, every time.
Tried it? Compare with the worked answer for Chapter 5.
What you’ve done
You turned one crowded package into three focused ones, decided what each shows to the world, and used an interface so the same Tracker works with a file or with memory. One set of tests checks every storage. You also handed the keyboard to the AI for the first time, and reviewed its work the way a senior developer would: scope first, then Go’s checks, then every line.
In Chapter 6, Tracker becomes a web API. The AI stays the implementer, building the HTTP handlers from your tests, and you’ll add one check command that runs all of Review in one go.