Senior
Should an interface be returned instead of a structure? When could this be an advantage?
sobes.tech AI
Answer from AI
Returning an interface instead of a concrete structure is advisable when you need to hide implementation details and provide only the necessary set of methods. This increases flexibility and makes it easier to replace the implementation without changing the client code.
Pros:
- Allows changing the internal implementation without altering the interface.
- Simplifies testing through mock objects.
- Promotes loose coupling and better abstraction.
Example:
// Interface
type Reader interface {
Read(p []byte) (n int, err error)
}
// Function returns an interface, hiding the concrete structure
func NewReader(data string) Reader {
return &stringReader{data: data}
}
// Client works with Reader, unaware of stringReader
However, if high performance is required and abstraction is not necessary, you can return a concrete structure.