Senior
Where is it better to define an interface — at the implementation site or at the usage site?
sobes.tech AI
Answer from AI
In Go, interfaces are better defined at the point of use rather than at the point of implementation. This allows creating minimal interfaces that describe only the methods actually needed by the consumer.
This approach increases flexibility and simplifies testing, as the implementation does not need to know about all interfaces, only those it requires.
Example:
// At the point of use
type Reader interface {
Read(p []byte) (n int, err error)
}
func Process(r Reader) {
// uses only the Read method
}
// At the point of implementation
type File struct {}
func (f *File) Read(p []byte) (int, error) {
// implementation
}
Thus, the interface is defined based on the client's needs, not the implementation.