Go

Interface Segregation — Small Interfaces

admin by @admin ADMIN
5d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
"The bigger the interface, the weaker the abstraction." Go encourages small, focused interfaces (often just one method) — io.Reader, io.Writer, fmt.Stringer. Define them at the consumer side.
Go
Raw
package main

import (
    "fmt"
    "io"
    "strings"
)

// Define interfaces where they\'re USED, not where they\'re implemented.
// This function works with anything that can be read from.
func WordCount(r io.Reader) (int, error) {
    buf := make([]byte, 1024)
    count, total := 0, 0
    for {
        n, err := r.Read(buf)
        for _, b := range buf[:n] {
            if b == ' ' || b == '\n' { count++ }
        }
        total += n
        if err == io.EOF { break }
        if err != nil    { return 0, err }
    }
    return count + 1, nil                          // last word
}

func main() {
    // Pass anything that implements io.Reader
    n, _ := WordCount(strings.NewReader("hello world foo bar"))
    fmt.Println("words:", n)                       // 4

    // Could also be a file, network connection, gzip stream, etc.
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.