Golang / GoLang Interfaces and Object Oriented Interview Questions
What is interface pollution and how do you avoid it in Go?
Interface pollution means creating interfaces prematurely, needlessly, or with too many methods — when a concrete type would be simpler and clearer. It adds indirection without benefit and makes code harder to navigate.
| Anti-pattern | Problem | Fix |
|---|---|---|
| Interface with one method per struct method | Exact mirror of the struct — no abstraction added | Use the concrete type directly |
| Interface defined by the implementor, not the consumer | Forces all callers to use the interface even if only one type exists | Define the interface in the consumer package |
| Interface used to add indirection to simple logic | Every call requires vtable dispatch for no benefit | Pass concrete type; extract interface when a second impl appears |
| Returning an interface from a constructor 'for flexibility' | Callers cannot access all methods; future changes break the contract | Return the concrete type; consumers can define their own interface |
// Interface pollution â unnecessary interface type UserGetter interface { GetUser(id int) User GetUserByEmail(email string) User GetUsersByGroup(group string) []User UpdateUser(u User) error DeleteUser(id int) error // ... 10 more methods } // If only ONE type will ever implement this, it adds noise // Better: define the interface where it's consumed, with minimum methods // In the notification package: type UserFetcher interface { // only what notifications need GetUser(id int) User } // Rule: define the interface in the CONSUMING package, not the producing package // (Often called the 'interface ownership' principle) // When interfaces are justified: // 1. Multiple concrete implementations exist (or are expected soon) // 2. Needed for testability (inject a mock) // 3. Standard library patterns (io.Reader, http.Handler) // 4. Plugin or extension points in a library // Go proverb: 'Don't design with interfaces, discover them.' // Start with concrete types; extract interfaces when the need becomes clear
The Go proverb "Don't design with interfaces, discover them" captures the idiomatic approach: write concrete types first. When a second concrete implementation is needed, or when testability requires a mock, extract an interface at that point. Premature abstraction costs readability without delivering flexibility.
More Related questions...