Senior
Tell about the use case of interfaces in production logic from an architectural perspective.
sobes.tech AI
Answer from AI
In production logic in Go, interfaces are often used to achieve loose coupling of components and ease of testing.
For example, in an application architecture, you can define an interface for the data access layer:
// UserRepository describes methods for working with users
type UserRepository interface {
GetUserByID(id int) (*User, error)
SaveUser(user *User) error
}
In the business logic (service layer), we accept this interface, not depending on a specific implementation (for example, a database or a mock for tests):
func NewUserService(repo UserRepository) *UserService {
return &UserService{repo: repo}
}
func (s *UserService) GetUserProfile(id int) (*UserProfile, error) {
user, err := s.repo.GetUserByID(id)
if err != nil {
return nil, err
}
// additional logic
return &UserProfile{User: user}, nil
}
This approach allows:
- Easily changing the repository implementation (for example, switching between databases or using mocks for tests).
- Isolating business logic from data storage details.
- Improving code readability and maintainability.
In production, this helps create flexible and scalable applications with clear separation of responsibilities.