Book Image

Hands-On Dependency Injection in Go

By : Corey Scott
Book Image

Hands-On Dependency Injection in Go

By: Corey Scott

Overview of this book

Hands-On Dependency Injection in Go takes you on a journey, teaching you about refactoring existing code to adopt dependency injection (DI) using various methods available in Go. Of the six methods introduced in this book, some are conventional, such as constructor or method injection, and some unconventional, such as just-in-time or config injection. Each method is explained in detail, focusing on their strengths and weaknesses, and is followed with a step-by-step example of how to apply it. With plenty of examples, you will learn how to leverage DI to transform code into something simple and flexible. You will also discover how to generate and leverage the dependency graph to spot and eliminate issues. Throughout the book, you will learn to leverage DI in combination with test stubs and mocks to test otherwise tricky or impossible scenarios. Hands-On Dependency Injection in Go takes a pragmatic approach and focuses heavily on the code, user experience, and how to achieve long-term benefits through incremental changes. By the end of this book, you will have produced clean code that’s easy to test.
Table of Contents (15 chapters)

Leave your baggage at the door

If you were to ask me what is the most frequent mistake new Go programmers make?, I would not hesitate to tell you that it's bringing other language patterns into Go. I know this was my biggest early mistake. My first Go service looked like a Java app written in Go. Not only was the result subpar but it was rather painful, particularly while I was trying to achieve things such as inheritance. I've had a similar experience programming Go in a functional style, as you might see in Node.js.

In short, please don't do it. Re-read Effective Go and Go blogs as often as you need to until you find yourself using small interfaces, firing off Go routines without reservation, loving channels, and wondering why you ever needed more than composition to achieve nice polymorphism.