Re:One Year After Switching from Java to Go: Our Experiences
by CharlieDigital on Wednesday February 19, 2025 @07:41AM
(#43101437)
.NET's DI has constructor injection so I suppose this is similar; you just write your constructor saying "I need an `IDataProvider`" and it can come from DI or direct.
Question I have for Go though. Without DI, what is the idiomatic way of supplying one of x implementations? An if-else block? Like if I had 5 possible implementations (AzureBlobStore, AwsBlobStore, GcpBlobStore, etc).
Re:One Year After Switching from Java to Go: Our Experiences
by dgunay on Wednesday February 19, 2025 @07:31PM
(#43109679)
Yeah it basically is just an if-else or switch block.
type BlobStore interface { /* methods */ }
// later, when initializing stuff
var foo BlobStore
switch {
case isAzure:
foo = AzureBlobStore{}
default:
foo = FSBlobStore{}
}
svc1 := NewSvc1(foo)
// Constructors are just functions and are totally
// convention/arbitrary. If the fields are public you
// can instantiate the struct directly.
svc2 := Svc2{ BlobStore: foo }
"DI" in the sense of having a more complex purpose-built DI container is less common. They exist, but I don't see them used a lot.
If your application code has a ton of dependencies, the direct injection/low magic style favored by Go can get kind of boilerplate-y. I'm not going to comment on which style is better.