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)

Chapter 2, SOLID Design Principles for Go

1. How does the single responsibility principle improve Go code?

By applying the single responsibility principle, the complexity of our code is reduced as it is decomposed code into smaller, more concise pieces.

With the smaller, more concise pieces, we gain increases in the potential usability of that same code. These smaller pieces are easier to compose into larger systems, due to their lighter requirements and more generic nature.

The single responsibility principle also makes tests simpler to write and maintain because when a piece of code has only one purpose, there is only much less scope (and therefore complexity) required to test.

 

2. How does the open/closed principle improve Go code?

The open/closed principle helps reduce the risk of additions and extensions by encouraging us not to change existing code, particularly exported...