Interface Composition and Best Practices
Small interfaces and dependency inversion
Interface Composition
Go interfaces can embed other interfaces to compose larger ones:
package main
import "io"
// io.ReadWriter composes Reader and Writer
type ReadWriter interface {
io.Reader
io.Writer
}
// Your own composition:
type Processor interface {
io.Reader
Process() error
io.Closer
}
func main() { _ = (*Processor)(nil) }Small Interface Principle
The most powerful Go interfaces have one or two methods. This maximizes the number of types that can satisfy them:
io.Reader— 1 methodio.Writer— 1 methoderror— 1 methodfmt.Stringer— 1 method
Large interfaces are harder to mock and test.
All lessons in this course
- Defining and Implementing Interfaces
- Core Standard Library Interfaces
- Type Assertions and Type Switches
- Interface Composition and Best Practices