Golang / GoLang Interfaces and Object Oriented Interview Questions
How does thinking about interfaces as 'behaviours, not data' guide better design?
In Go, the best interfaces describe what something does, not what something is. Names ending in -er (Reader, Writer, Closer, Logger, Handler) signal a single behaviour. This contrasts with Java-style interfaces like IUserRepository that mirror a class's public API.
// Behaviour-based (Go idiomatic) type Logger interface { Log(msg string) } // what it does type Notifier interface { Notify(event Event) } // what it does type Closer interface { Close() error } // what it does // Data/entity-based (anti-pattern in Go) type IUserRepository interface { // describes a whole entity FindByID(id int) (*User, error) FindByEmail(email string) (*User, error) Save(u *User) error Delete(id int) error Count() int } // Problem: every consumer is forced to implement or mock ALL 5 methods // even if they only need FindByID // Better: define the minimum interface in the consumer // package email â only needs to look up users type UserLookup interface { FindByEmail(string) (*User, error) } // package reporting â only needs to count type UserCounter interface { Count() int } // The concrete *UserRepo satisfies all of the above // without knowing about any of them // Naming: prefer -er suffix for single-method interfaces // io.Reader, io.Writer, io.Closer â the standard library gold standard // fmt.Stringer, sort.Interface, http.Handler
The behaviour framing also makes mocking trivial. If your function needs only UserLookup, the mock has one method. If it needs the full IUserRepository, the mock has five. Narrow, behaviour-focused interfaces dramatically reduce test maintenance burden.
More Related questions...