Why I like Go interfaces

    Not so long ago, I started learning Go and found that there, many seemingly familiar things work differently. Interfaces are among them. Previously, I did not think about the fact 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 that has largely determined my attitude to interfaces in Go.

    Go is quite a solid language


    Sorry for the pun, I 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 is raised, they talk about SOLID principles and generally rarely about the last (in order, but not in importance) of them - the principle of dependency inversion (DIP). If forgotten, then it is usually formulated as follows:
    Abstractions should not depend on the details. Details must depend on abstractions.
    Probably the most powerful tool that was invented to implement this principle - interfaces. If you want to clarify the inverse of dependencies for yourself, then here is a good article . By the way, the picture is from there.



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

    A few words in the end


    Interfaces in Go is a powerful tool, including for dependency inversion. But do not create them for everything, so every time ask yourself - why are you doing this.

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

    Also popular now: