Go's 'Define Interfaces Where You Use Them' Rule Keeps APIs Small and Testable

In Go, the recommended practice is to define interfaces in the package that consumes them, not in the package that produces the concrete type. This contrasts with object-oriented languages like Java and C#, where interfaces are typically declared alongside their implementations. By declaring only the methods a package actually needs, developers shrink dependencies — for example, an email sender that uses one method should depend on a one-method interface, not a fourteen-method store interface. Smaller interfaces also make unit testing easier, since faking a single method requires just a few lines of code rather than a generated mock. This approach additionally prevents import cycles, as consumer-defined interfaces remove the need for packages to import each other by name.
This is an AI-generated summary. ShortSingh links to the original source for the complete article.
Discussion (0)
Log in to join the discussion and vote.
Log in