When working with Go in an industrial context, I feel like dependency injection (DI) often gets a bad rep because of DI frameworks. But DI as a technique is quite useful. It just tends to get explained with too many OO jargons and triggers PTSD among those who came to Go to escape GoF theology.Dependency Injection is a 25-dollar term for a 5-cent concept.— James ShoreDI basically means passing values into a constructor instead of creating them inside it. That’s really it. Observe:type server struct { db DB } // NewServer constructs a server instance func NewServer() *server { db := DB{} // The dependency is created here return &server{db: db} } Here, NewServer creates its own DB. Instead, to inject the dependency, build DB elsewhere and pass it in as a constructor parameter:func NewServer(db DB) *server { return &server{db: db} } Now the constructor no longer decides how a database is built; it simply receives one.In Go, DI is often done using interfaces. You collate the behavior you care about in an interface, and then provide different concrete implementations for different contexts. In production, you pass a real implementation of DB. In unit tests, you pass a fake implementation that behaves the same way from the caller’s perspective but avoids real database calls.Here’s how that looks:// behaviour we care about type DB interface { Get(id string) (string, error) Save(id, value string) error } type server struct{ db DB } // NewServer accepts a concrete implementation of the DB interface in runtime // and passes it to the server struct. func NewServer(db DB) *server { return &server{db: db} } A real implementation of DB might look like this:type RealDB struct{ url string } func NewDB(url string) *RealDB { return &RealDB{url: url} } func (r *RealDB) Get(id string) (string, error) { // pretend we hit Postgres return "real value", nil } func (r *RealDB) Save(id, value string) error { return nil } And a fake implementation for unit tests might be:type FakeDB struct{ d...
First seen: 2025-05-25 08:43
Last seen: 2025-05-26 06:47