CodeGym /행동 /Go SELF /Layers: domain → app/usecases → adapters

Layers: domain → app/usecases → adapters

Go SELF
레벨 28, 레슨 0
사용 가능

1. Layer diagram and direction of dependencies

When you are just starting out, it is tempting to do this: main.go, 400 lines in it, everything nearby, everything “at hand.” At some point that even works — roughly until the first serious change, when you need to add a new feature and you do not understand what will break if you move one line. It is like fixing a bicycle whose handlebars are bolted to the pedals: technically it moves, but only in a straight line and only until you blink.

Layers help break that strange mechanism. They give you a simple idea: code is grouped by role, and dependencies are directed “from the inside out.” And most importantly: in Go, the compiler directly participates in the discipline — through imports. import is not just “connect functions,” it is an agreement to depend on someone else’s API at compile time.

Minimal layer map: domain → app/usecases → adapters

If you have heard the word “architecture” and imagine a department where people in black turtlenecks sit and argue about UML until the bitter end — you are not alone. But today we have the architecture version for ordinary mortals: three layers that can be explained on your fingers and maintained without ritual dance.

Let us agree on the terms (they are very practical):

Layer What lives in it What should not be in it
domain (domain/model) business data and rules: entities, invariants input/output, files, HTTP, fmt.Println “just in case”
app / usecases (scenarios) application-level operations: “create a task,” “find a task,” “mark as done” specific databases, specific CLI/HTTP, global state
adapters (adapters) concrete implementations: memory, file, database, CLI wrapper, HTTP wrapper business rules of “how it should be” (they are not here)

The key idea: the same scenarios (app/usecases) can be connected to CLI, HTTP, and tests because scenarios communicate with the outside world through interfaces, not through concrete implementation packages. But today we are talking about the idea of layers and import directions; we will keep the magic of dependency injection to a minimum, without complications.

Direction of dependencies: the outer knows about the inner

Now comes a phrase that is useful to keep in your head like a road sign: dependencies are directed from the outside to the inside. That is, CLI/HTTP/storage know about app and domain, scenarios know about domain, and domain does not know about anyone at all — it is like a wise cat: it simply exists and follows its own rules.

Why does this matter? Because otherwise you get a “spaghetti import graph”: one package imports the second, the second imports the third, the third suddenly imports the first, and the compiler gives you a stern “no.” And the compiler is right: cyclic imports almost always mean you have mixed up responsibility.

It is convenient to think of it like this:

flowchart LR
    domain[domain: entities and rules]
    app[app/usecases: scenarios]
    adapters[adapters: storage/cli/http]

    adapters --> app
    app --> domain

If your arrow suddenly goes the other way (for example, domain imports adapters) — that is not “well, it happens,” that is a signal: you are trying to shove infrastructure details into a place where only rules should be.

Import as a dependency at compile time

In Go, an import is not just “give me a function.” When you import a package, you start depending on its exported API. And that is not philosophy — it is a very practical contract that is hard to change without consequences.

Of course, we are not writing the standard library, but the principle is the same: the more you export and the more packages import it, the harder it is to change the code.

From this comes an important connection to the layer topic: layers reduce the number of “dangerous” dependencies. For example, if the CLI layer depends on app, then changing the CLI should not force you to rewrite the domain. And if the domain suddenly starts depending on the CLI — congratulations, you have invented “business rules depend on terminal hint text.” That sounds funny, but in real code such things appear unnoticed.

3. import path and module path in your own packages

Now comes a small terminology frame — without commands and without diving deeply into Go Modules. It is simply important to understand why imports of your own packages look “long”.

In Go, there is a string you write in import "...". That is the import path. For external libraries, it usually looks like a URL: domain + path, for example "golang.org/x/oauth2". This import style has been used in the Go ecosystem for many years.

For your own packages, the import path usually starts with the module path — the string specified in go.mod after the word module. We are not running commands and we are not discussing version management, but let us pin down the term: module path is the prefix from which your package imports are built.

Let us imagine that the project’s module path is this:

example.com/tasker

Then the imports of your packages will look something like this:

import "example.com/tasker/domain"
import "example.com/tasker/app"
import "example.com/tasker/adapters/memstore"

And that is normal. Yes, it is long. But it is unambiguous: in a large project there will not be “two different domain packages from different places.”

4. Example: the Tasker mini application

Directory structure

To keep the layers from being an abstract lecture, let us build a small application that can be extended later: a task manager called tasker. Today we will lay down only the scaffold and minimal types, so we can see how layers are reflected in the file structure and imports.

Here is the project “skeleton” (as an idea):

tasker/
  go.mod                  (module example.com/tasker)
  main.go
  domain/
    task.go
  app/
    add_task.go
  adapters/
    memstore/
      store.go

Important point: this structure is not a religion. It is just a convenient way to make the role visible from the path. We could have named app as usecases, could have named domain as model, could have named adapters as infra. Today we are fixing the idea, not the one and only correct naming.

The domain layer: the Task entity and the rule “title must not be empty”

Domain types are what you want to have even in a world with no terminal, no server, no files, and no database. If tomorrow your CLI disappears, the domain should still describe your business area. That is why in the domain we keep the Task structure and a minimal rule: the title must not be empty.

File domain/task.go:

package domain

import "errors"

var ErrEmptyTitle = errors.New("empty title")

type Task struct {
	ID    int
	Title string
	Done  bool
}

func NewTask(id int, title string) (Task, error) {
	if title == "" {
		return Task{}, ErrEmptyTitle
	}
	return Task{ID: id, Title: title}, nil
}

Notice a few things. We do not print anything to the console. We do not read files. We return an error because the domain is not the place where you decide exactly how to tell the user about a problem. And yes, ErrEmptyTitle is exported: it is part of the domain’s meaning, and higher layers can make decisions based on it.

The app/usecases layer: the task-addition scenario and a dependency interface

A scenario is “what the application does,” but without the details of “how exactly it stores data” and “through which interface the user clicks buttons.” Here we describe the task addition operation. And we need a dependency: a place to store things. But we do not want to pull a concrete implementation (for example, in-memory or file-based) directly into the scenario.

So the scenario declares an interface — the minimal contract it needs.

File app/add_task.go:

package app

import (
	"context"
	"fmt"

	"example.com/tasker/domain"
)

type TaskStore interface {
	NextID(ctx context.Context) (int, error)
	Save(ctx context.Context, t domain.Task) error
}

func AddTask(ctx context.Context, store TaskStore, title string) (domain.Task, error) {
	id, err := store.NextID(ctx)
	if err != nil {
		return domain.Task{}, fmt.Errorf("next id: %w", err)
	}

	t, err := domain.NewTask(id, title)
	if err != nil {
		return domain.Task{}, err
	}

	if err := store.Save(ctx, t); err != nil {
		return domain.Task{}, fmt.Errorf("save task: %w", err)
	}
	return t, nil
}

Here we are doing an important architectural thing: app imports domain, but does not import any adapters. This allows us to later plug in any TaskStore implementation. And yes, context.Context may still look like “an extra parameter,” but it is an investment: the scenario starts to look like a proper application operation.

The adapters layer: an in-memory store for the required interface

An adapter is where details appear. For example, storing data in memory. It may not be perfect and may not even be permanent (everything disappears after restart), but it is simple. And most importantly: this is not part of the domain and not part of the scenario. It is just one way to satisfy the interface.

File adapters/memstore/store.go:

package memstore

import (
	"context"

	"example.com/tasker/domain"
)

type Store struct {
	next int
	data map[int]domain.Task
}

func New() *Store {
	return &Store{next: 1, data: make(map[int]domain.Task)}
}

Let us continue with the methods the scenario needs:

func (s *Store) NextID(ctx context.Context) (int, error) {
	id := s.next
	s.next++
	return id, nil
}

func (s *Store) Save(ctx context.Context, t domain.Task) error {
	s.data[t.ID] = t
	return nil
}

Notice: the memstore package imports domain because it stores a domain entity. But it does not import app. That is also part of the direction of dependencies: the adapter implements the contract, but the contract lives “above” (from the consumer side). Today it is enough to fix this as an idea, without subtle debates about “where the interface should live.”

main as the place where layers meet

When you first see layers, the question arises: “so where do we assemble all this?” The answer is grounded: in main. The application entry point is the place where it is acceptable to connect details. That is not an “architectural sin,” it is main’s job: choose implementations and run scenarios.

File main.go:

package main

import (
	"context"
	"fmt"

	"example.com/tasker/adapters/memstore"
	"example.com/tasker/app"
)

func main() {
	store := memstore.New()

	t, err := app.AddTask(context.Background(), store, "read Go book")
	if err != nil {
		fmt.Println("error:", err)
		return
	}

	fmt.Printf("added: #%d %s\n", t.ID, t.Title) // added: #1 read Go book
}

Here we saw the reason we built layers: main imports the adapter and app, while app does not know what memstore is at all. If later you want to store tasks in a file or database, the scenario logic should not have to be rewritten.

How to read a project through imports

When a project grows, you rarely read all the code in sequence. More often you read the directory structure and the imports. It is almost like looking at a subway map: you care about where you can go without a transfer and where transfers are forbidden.

Useful self-check for our example:

flowchart TD
    main[main] --> appPkg[app]
    main --> mem[memstore]
    appPkg --> domainPkg[domain]
    mem --> domainPkg

If you saw an arrow domain -> app or domain -> memstore, then the domain has “leaked” infrastructure. If you saw app -> memstore, then the scenario has started to depend on specifics and lost its meaning as portable logic. If you saw a cycle — the compiler will stop you, and that will be the best “gift” of the day.

5. Typical mistakes when introducing layers

Mistake #1: making “layers for the sake of layers” without a real reason.
Sometimes people read too much about architecture and start splitting even a 50-line program into ten packages. In the end you do not get flexibility, but you do get navigation complexity. Layers are useful when an application has at least two different “outside worlds” (for example, CLI today, HTTP tomorrow) or when business logic starts repeating and you want to keep it in one place.

Mistake #2: the domain starts doing input/output.
The most common way to “break” the layer idea is to add something like fmt.Println("task created") or file reading “for convenience” into domain. The domain should be boring: structures, methods, rule checks, errors. As soon as I/O appears in the domain, it becomes dependent on the environment and stops being a portable core.

Mistake #3: the scenario imports a concrete adapter implementation.
It looks harmless: “well, I need to save a task, I’ll just import memstore and that is it.” But that is exactly the point where the scenario stops being a scenario and becomes “an application permanently glued to memory.” The correct path is to depend on an interface and receive the implementation from outside, even if it looks a bit more verbose for now.

Mistake #4: confusing package name with import path.
Beginners sometimes think a package must be named exactly like the last part of the import path. Usually that is how it is done, but it is not the same thing. The import path is the “address” where the package is located, and the package name is how you refer to it in code. Because of that, strange imports and aliases sometimes appear. Do not be alarmed: this is a normal part of a project growing up.

Mistake #5: trying to solve all architectural questions at once.
The temptation is to do everything at once: perfect domain, beautiful scenarios, universal adapters, tests, a DI container, and the compiler applauding standing up. In practice it is more useful to move in small steps: first separate the domain, then the scenarios, then the adapters. Layers are not the goal, but a way to keep complexity on a leash before it eats your brain.

1
과제
Go SELF, 레벨 28, 레슨 0
잠금
사용자 여권
사용자 여권
1
과제
Go SELF, 레벨 28, 레슨 0
잠금
할 일 추가
할 일 추가
1
과제
Go SELF, 레벨 28, 레슨 0
잠금
포켓 라이브러리
포켓 라이브러리
1
과제
Go SELF, 레벨 28, 레슨 0
잠금
콘솔 노트
콘솔 노트
코멘트
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION