Practice — CRUD layouts
Flat, by layer, by domain, and the four-file CRUD shape.
You are writing a 300-line tool with one job. Which layout fits?
All questions with explanations (answers shown)
1. You are writing a 300-line tool with one job. Which layout fits?
Answer: Flat: one package, a few files
Start flat. Layout should match the size of the problem, and a 300-line tool does not need folders.
2. Your layer-grouped app (
models/,services/,handlers/) has grown to a dozen features and you hit an import cycle. What is the usual next step?Answer: Move to one folder per domain, like
user/andorder/, each holding its own model, service and handlerGrouping by layer spreads one feature across many folders and invites cycles. Grouping by domain keeps a feature together and dependencies point one way.
3. How should Go packages be organised in a service?
Answer: By domain:
user/,note/, each holding its own model, repo, service and handlerLayer-based layouts mean every feature touches five folders and every package imports every other. A domain package can be read, tested and deleted on its own.
4. What does the
internal/directory do?Answer: The compiler forbids anything outside your module from importing it
The Go toolchain enforces it. Put everything that is not meant to be a public API under it and you get that boundary for free.
5. Why does
mainusually just call arun() errorfunction?Answer: Because
os.Exitskips deferred calls, so you want exactly oneos.Exit, at the topWith
os.Exitscattered throughmain, yourdefer db.Close()never runs. One exit point at the top keeps every defer working.6. Which is the correct dependency direction?
Answer: handler → service → repository
Dependencies point inward. The repository never imports
net/http; the service never touches a SQL dialect. That is what makes each layer testable alone.