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 Pinger
Each 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.
More Related questions...