📜 ⬆️ ⬇️

Why I like Go interfaces

Not so long ago, I began to study Go and found that there are many seemingly familiar things that work differently. Interfaces are among them. Previously, I did not think that duck typing can be in a statically typed language. Now it seems to me that this is logical and reasonable. Here I will describe one reason, which to a greater degree determined my attitude to the interfaces in Go.

Go quite SOLID'ny language


Sorry for the pun, could not resist

On the topic "Is Go an object-oriented language?" A lot of articles have been written, including on Habré. But not so often, when this topic rises, they talk about SOLID principles and rarely about the last (in order, but not least) of them - the principle of dependence inversion (DIP). If forgotten, it is usually formulated as follows:
Abstractions should not depend on the details. Details must depend on abstractions.
Probably the most powerful tool that came up with to implement this principle - interfaces. If you want to clarify for yourself the inversion of dependencies, here is a good article . By the way the picture from there.


')
Suppose that Foo and Bar are in different modules: F and B. But then, to implement the interface, we have to import the IBar interface into B from F, and then somehow implement its implementation back to F. In a sense, a cyclic dependence between packages (not in terms of behavior, but in terms of importing). This is where the implicit implementation of interfaces comes to our rescue. We can import Bar from B to F, and Go will figure out by itself whether it implements IBar or not. In such a case, explicitly specifying the interfaces becomes redundant when implemented.

A couple of words for last


Interfaces in Go are a powerful tool, including dependency inversion. But you should not create them for everything in a row, so ask yourself every time why you do it.

What do you like / dislike about the Go type system?

Source: https://habr.com/ru/post/451240/


All Articles