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)

When the magic fades

Earlier in the book, I challenged you to examine each method of DI presented in the book with a critical eye. With that in mind, we should consider the potential costs of monkey patching.

Data races—We saw in our examples that monkey patching is the process of replacing a global variable with a copy that performs in the way we need it to for a particular test. And that is perhaps the biggest problem. Swapping something global, and therefore shared, for something specific causes a data race on that variable.

To understand this data race a little more, we need to understand how Go runs tests. By default, tests within a package are executed sequentially. We can reduce our test execution time by marking our tests with t.Parallel(). With our current tests of the data package, marking the test as parallel would cause the data race to appear, resulting in...