Dependency Inversion Principle (D)

The final principle is the Dependency Inversion Principle, which states the following:

"Depend on abstractions, not on concretions."

This means that higher-level modules should depend only on interfaces and not on concrete implementations. In Java, huge frameworks such as Spring have come up as dependency injection capabilities so that beans (objects) can be injected into the application at runtime, while the rest of the code just works with interfaces of the beans (rather than the concrete implementations).

In Go, this principle boils down to two recommendations:

  • Every package should have interfaces that advertise functionality without the implementation specifics.
  • When a package needs a dependency, it should take that dependency as a parameter.

To illustrate the second point, let's say we have built two packages (layers) for the search microservice of our travel website:

  • Service layer: This layer has a lot of the business logic for the searching and sorting.
  • Communication layer: This layer is just responsible for getting data from different sellers. Each seller has its own API, and thus this layer has a lot of different implementations of a SellerCommunication interface.

According to this principle, we should be able to inject a specific instantiation of the communication layer to the service layer. The injection of the concrete implementation of the communication layer can be done through the driver's main function. This allows the service layer to function just knowing (depending on) on the SellerCommunication interface and not on a specific implementation. One way to immediately exploit this is mocking—the SellerDAO interface can be mocked for test cases of the service layer components.

With these principles in mind, let's look at specific design patterns, beginning with creational design patterns.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset