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.HandlerThe 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.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
