Advantages of method injection

As we saw in the previous section, method injection is used extensively in the standard library. It is also extremely useful when you want to write your own shared libraries or frameworks. Its usefulness does not stop there.

It is excellent with functions—Everybody loves a good function, particularly those that follow the Single responsibility principle section, as discussed in Chapter 2, SOLID Design Principles for Go. They're simple, stateless, and can be highly reusable. Adding method injection to a function will increase its reusability by converting the dependency into an abstraction. Consider the following HTTP handler:

func HandlerV1(response http.ResponseWriter, request *http.Request) {   garfield := & ...

Get Hands-On Dependency Injection in Go now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.