Where to declare an interface
Accept interfaces, return concrete types. An interface lives with the code that uses it.
A practical rule that comes up in review: accept interfaces, return structs (or other concrete types).
The function func Save(w io.Writer, data []byte) error does not know whether this is a file, the network, or a buffer in a test. It needs only Write. Returning the interface io.Reader makes sense when the concrete type is truly hidden and the caller has no more honest API. Returning an interface "just in case", when one struct sits behind it, hides fields and methods the caller needs and forces a type assertion.
An interface is declared in the consumer package. If the HTTP layer knows how to read users, the interface UserStore lives next to the handler, not inside the Postgres package. Then Postgres does not depend on HTTP, and the handler test substitutes a small stub without bringing up a database. The opposite direction — the database package declares a huge interface and implements it itself — gives nothing except an extra name.
Do not extract an interface until there is a second use, or a test that hurts without it. An interface for a single implementation is noise. Start with a concrete type. When a seam appears, cut the interface to the actual calls, and it will come out small.
io.Reader and io.Writer are the model. One method, no knowledge of a file. Code that copies bytes does not import os. That is the Middle sense of taste: a dependency on behavior, not on the package that happened to implement that behavior.
Practice
What to accept
A function only writes bytes to an unknown place. What is better to put in the parameter?
- *os.File
- io.Writer
- any
- A string with a path to a file
Which package an interface lives in
A handler calls two methods of a store. Where should the interface of those two methods be declared?
- In the handler package, following the actual calls
- In the database package, next to the single implementation
- In a separate models package, where every interface of the project lives
- Nowhere. The handler should accept *sql.DB
When an interface is early
Mark the situations where an interface is not needed yet.
- There is exactly one type, and the test constructs it calmly
- You want an interfaces folder for growth
- Otherwise the handler test would have to bring up a database
- Two implementations already exist