Sobes.tech
Senior

Are there any advantages to the approach of extracting interfaces into a separate package?

sobes.tech AI

Answer from AI

Extracting interfaces into a separate package in Go has several advantages:

  • Clean architecture and separation of concerns. Interfaces that define contracts are separated from concrete implementations, making the code easier to understand and maintain.
  • Simplified testing. With separate interfaces, it is easy to replace implementations with mocks or stubs.
  • Reduced dependencies. Packages that use interfaces depend only on the contracts, not on specific implementations, which reduces coupling.
  • Increased reusability. Interfaces in a separate package can be used by different modules without duplication.

However, it is important to avoid excessive package fragmentation to prevent complicating the project structure.

Example:

// In the interfaces package
package interfaces

type Storage interface {
    Save(data []byte) error
    Load(id string) ([]byte, error)
}

// In the storage package
package storage

import "project/interfaces"

type FileStorage struct {}

func (fs *FileStorage) Save(data []byte) error { /* implementation */ return nil }
func (fs *FileStorage) Load(id string) ([]byte, error) { /* implementation */ return nil, nil }

var _ interfaces.Storage = (*FileStorage)(nil) // interface compliance check