Golang / GoLang Interfaces and Object Oriented Interview Questions
How does Go embody the Interface Segregation Principle (ISP)?
The Interface Segregation Principle states: clients should not be forced to depend on methods they do not use. Go's implicit, structural interfaces make ISP trivially achievable — any consumer can define the minimal interface it needs, independently of what the concrete type exposes.
// A concrete type with many methods (a real storage backend)
type RedisClient struct{ pool *redis.Pool }
func (r *RedisClient) Get(key string) (string, error) { /* ... */ return "", nil }
func (r *RedisClient) Set(key, val string, ttl time.Duration) error { /* ... */ return nil }
func (r *RedisClient) Delete(key string) error { /* ... */ return nil }
func (r *RedisClient) Increment(key string) (int64, error) { /* ... */ return 0, nil }
func (r *RedisClient) Expire(key string, d time.Duration) error { /* ... */ return nil }
func (r *RedisClient) Ping() error { /* ... */ return nil }
// Package: cache — only needs Get and Set
type Getter interface{ Get(key string) (string, error) }
type Setter interface{ Set(key, val string, ttl time.Duration) error }
type Cache interface { Getter; Setter } // composed
func newCacheLayer(c Cache) *CacheLayer { return &CacheLayer{c: c} }
// Package: rate-limiter — only needs Increment and Expire
type Counter interface {
Increment(key string) (int64, error)
Expire(key string, d time.Duration) error
}
func newRateLimiter(c Counter) *RateLimiter { return &RateLimiter{c: c} }
// Package: health — only needs Ping
type Pinger interface{ Ping() error }
func newHealthCheck(p Pinger) *HealthCheck { return &HealthCheck{p: p} }
// RedisClient satisfies ALL of Cache, Counter, and Pinger
redis := &RedisClient{pool: pool}
cache := newCacheLayer(redis) // passes as Cache
limiter := newRateLimiter(redis) // passes as Counter
health := newHealthCheck(redis) // passes as PingerEach consumer defines its own minimal interface — without RedisClient knowing about any of them. Adding a new consumer with a new subset of methods requires zero changes to RedisClient. This is ISP at its most natural: Go's structural typing makes it the path of least resistance.
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...
