CLI — Domain and Storage
What you will learn
By the end of this checkpoint, you will be able to:
- keep task rules separate from file mechanics;
- assign stable increasing IDs;
- avoid mutating storage-owned slices accidentally;
- write JSON through a temporary file;
- test domain rules with an in-memory fake.
Build the service
type Clock func() time.Time
type Service struct {
store Store
now Clock
}
func NewService(store Store, now Clock) (*Service, error) {
if store == nil {
return nil, errors.New("store is required")
}
if now == nil {
return nil, errors.New("clock is required")
}
return &Service{store: store, now: now}, nil
}
The clock is injected so tests can make creation times deterministic.
Add a task
func (s *Service) Add(ctx context.Context, title string) (Task, error) {
title = strings.TrimSpace(title)
if title == "" {
return Task{}, errors.New("task title must not be empty")
}
tasks, err := s.store.Load(ctx)
if err != nil {
return Task{}, fmt.Errorf("load tasks: %w", err)
}
task := Task{
ID: nextID(tasks),
Title: title,
CreatedAt: s.now().UTC(),
}
tasks = append(tasks, task)
if err := s.store.Save(ctx, tasks); err != nil {
return Task{}, fmt.Errorf("save tasks: %w", err)
}
return task, nil
}
func nextID(tasks []Task) ID {
var maximum ID
for _, task := range tasks {
if task.ID > maximum {
maximum = task.ID
}
}
return maximum + 1
}
Scanning is sufficient for a learning project. A real multi-process store would need atomic ID allocation at the persistence layer.
Update by index after finding by ID
var ErrNotFound = errors.New("task not found")
func findIndex(tasks []Task, id ID) (int, error) {
for index := range tasks {
if tasks[index].ID == id {
return index, nil
}
}
return -1, ErrNotFound
}
func (s *Service) Complete(ctx context.Context, id ID) error {
tasks, err := s.store.Load(ctx)
if err != nil {
return fmt.Errorf("load tasks: %w", err)
}
index, err := findIndex(tasks, id)
if err != nil {
return err
}
tasks[index].Completed = true
if err := s.store.Save(ctx, tasks); err != nil {
return fmt.Errorf("save tasks: %w", err)
}
return nil
}
Remove without preserving the removed slot
tasks = append(tasks[:index], tasks[index+1:]...)
This preserves order. It may retain references in the backing array for element types that contain pointers. Clear the unused final element when retention matters; for this small Task value the practical effect is limited.
File store ownership
type FileStore struct {
path string
mu sync.Mutex
}
The mutex protects concurrent access inside one process. It does not coordinate several processes writing the same file.
Load safely
func (s *FileStore) Load(ctx context.Context) ([]Task, error) {
if err := ctx.Err(); err != nil {
return nil, err
}
s.mu.Lock()
defer s.mu.Unlock()
data, err := os.ReadFile(s.path)
if errors.Is(err, os.ErrNotExist) {
return []Task{}, nil
}
if err != nil {
return nil, fmt.Errorf("read %q: %w", s.path, err)
}
var tasks []Task
if err := json.Unmarshal(data, &tasks); err != nil {
return nil, fmt.Errorf("decode %q: %w", s.path, err)
}
return tasks, nil
}
The context check can avoid starting work after cancellation, but os.ReadFile itself is not context-aware.
Replace through a temporary file
func writeJSONFile(path string, tasks []Task) (err error) {
directory := filepath.Dir(path)
temporary, err := os.CreateTemp(directory, ".tasks-*.tmp")
if err != nil {
return err
}
temporaryName := temporary.Name()
defer func() {
temporary.Close()
if err != nil {
_ = os.Remove(temporaryName)
}
}()
encoder := json.NewEncoder(temporary)
encoder.SetIndent("", " ")
if err = encoder.Encode(tasks); err != nil {
return fmt.Errorf("encode temporary task file: %w", err)
}
if err = temporary.Sync(); err != nil {
return fmt.Errorf("sync temporary task file: %w", err)
}
if err = temporary.Close(); err != nil {
return fmt.Errorf("close temporary task file: %w", err)
}
if err = os.Rename(temporaryName, path); err != nil {
return fmt.Errorf("replace task file: %w", err)
}
return nil
}
Rename and durability semantics vary by operating system and filesystem. This is safer than truncating the target first, but it is not a universal transactional-storage implementation. Production-grade durable files may also require syncing the directory and handling platform-specific replacement behaviour.
Practice checkpoint
Implement List, Complete, and Remove. Create an in-memory store that copies slices at its boundary, then test empty titles, increasing IDs, missing IDs, idempotent completion, removal order, and storage errors.
type memoryStore struct {
tasks []Task
loadErr error
saveErr error
}
func (s *memoryStore) Load(context.Context) ([]Task, error) {
if s.loadErr != nil {
return nil, s.loadErr
}
return slices.Clone(s.tasks), nil
}
func (s *memoryStore) Save(_ context.Context, tasks []Task) error {
if s.saveErr != nil {
return s.saveErr
}
s.tasks = slices.Clone(tasks)
return nil
}
Cloning prevents the service and fake from sharing the same slice header/backing storage accidentally. Tests can inject a fixed clock and compare complete task values.
Summary
- Domain services own validation and task rules.
- Inject time and storage so tests control external behaviour.
- A process mutex does not provide multi-process file safety.
- Temporary-write-and-rename reduces partial-file risk but remains filesystem-dependent.
- Fakes should preserve real ownership boundaries rather than exposing shared slices.
Ready to wrap up?
Mark this complete when you can explain the main idea and finish the practice task.