Join us

Dependency injection in Golang

0_5L4RqWmahah7aNhY.png

DI (Dependency Injection) is a technique when your modules receive dependency indirectly. They don’t know about the implementation of dependency, only about the interface. DI can help us to write low coupling code. It means that you would be able to exchange your code whenever you want, and it helps to reuse some of their parts.

Today I am going to talk about Dependency Injection in Golang.

What is it?

DI (Dependency Injection) is a technique when your modules receive dependency indirectly. They don’t know about the implementation of dependency, only about the interface.

Why do we need it?

DI can help us to write low coupling code. It means that you would be able to exchange your code whenever you want, and it helps to reuse some of their parts.

Example

We have a tiny project: main.go and two services — logger and cache

How do they work? We have a cache service which can be used if you want to store something in fast storage like Redis.

As you may see, the Cache service knows nothing about logger except the method that Cache needs. We don’t import anything, just describe the interface with two methods, Error(error) and Info(string).

Look at the Logger:

So, now we have to use it all together in main.go:

Let’s summarize

We've created two low coupled services which can work with any other Loggers and SentryClients, for example, we can use logger for tests that write to file or stdout.

Bonus

If you want to write tests, DI also can help you! Sometimes you need mocks for tests (to be independent of some modules like a logger in tests), you have to generate them! There is an amazing tool for this task in go — GoMock. When you describe only needed methods in DI interface, the GoMock generate mocks just for those methods — it is faster and more readable in practice than hundreds of methods in mocks.


Only registered users can post comments. Please, login or signup.

Start blogging about your favorite technologies, reach more readers and earn rewards!

Join other developers and claim your FAUN account now!

Avatar

Matt Tarasov

Software Engineer, Space307

@dryrainbow
Software engineer
User Popularity
10

Influence

1k

Total Hits

1

Posts