Sobes.tech
Senior

Waar is het beter om de interface te definiëren — op de implementatieplek of op de gebruiksplek?

sobes.tech AI

Antwoord van AI

In Go is it better to define interfaces 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 needs.

Example:

// At the point of use
type Reader interface {
    Read(p []byte) (n int, err error)
}

func Process(r Reader) {
    // only uses 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 needs of the client, not the implementation.