Sobes.tech
Senior

Why is the approach of declaring interfaces in a separate package worse than declaring them in place of use?

sobes.tech AI

Answer from AI

Declaring interfaces in a separate package often leads to excessive coupling and complicates code maintenance. The main reasons why declaring interfaces at the point of use is better:

  • The interface reflects the specific needs of the client. Declaring the interface where it is used, you precisely define the minimal set of methods required.

  • Reduces coupling between packages. If the interface is declared in a separate package, all implementations and clients depend on this package, which complicates refactoring.

  • Simplifies testing. It is easier to create mock objects for interfaces declared alongside the code that uses them.

  • Improves readability. The developer immediately sees what methods are needed without switching to another package.

Example:

// Bad: interface in a separate package
package storage

type Reader interface {
    Read(p []byte) (n int, err error)
}

// Good: interface declared at the point of use
package processor

func Process(r io.Reader) {
    // use r
}

Thus, declaring interfaces at the point of use promotes a more flexible and maintainable architecture.