Going total decoupled with type alias
How to completely decouple two packages using interfaces and type aliases
Let me put this DISCLAIMER here: On this text you will find a lot of utterly disgusting design choices, do not implement this, please, I am serious. That being said, there I go.
Interfaces are the way to go in go. While looking at the news on Go 1.9 I saw that now the language supports type aliases and that brought me an idea. To develop two packages that are able to interact with each other without any cross reference or coupling. First let’s try with a naive implementation that won’t work:
Explaining what we have above: we have a package called person, in this package we define a struct Person that contains a Pack property pointing to a Packer interface. A Packer must support to Pack something(called Object on the example). At this point the Pack property on the Person struct may be a BackPack or a SuitCase, we don’t care as long as it implements the right Pack method.
Lets have a look at our BackPack implementation:
As you may notice, we have again the definition of the Object interface. If we want to make sure that both packages work together without knowing about each other we need to have this double definition(I told you about disgusting design and poor choices). We could define the Object interface in a third package but then where the fun would be? I don’t want to couple these two packages not even through a third package, that is my goal, and you have to forgive me. I want to have a person that has a pack that is capable of storing objects with different weights, you got the idea.
Our main file looks like:
Done! One extra spaghetti code has born. If we try to run this program we will receive the following catastrophic message:
Even though both Object interfaces have the same implementation(are equal in declaration) they are different, backpack.Object != person.Object, that is what the error message says.You may find some extra information on this behavior here:
Go was born out of frustration with existing languages and environments for systems programming. Programming had become…golang.org
As I said before, while I was reading the news on Go 1.9 i saw that now the language supports type aliases and that sparked a new idea, why not put pineapple sauce over the spaghetti and try to create aliases to anonymous interfaces, the resulting code looks like:
See that extra “=” signal on line 3, now we do the same on the backpack.go:
Now we can run the same main.go without any issue. What is the difference? Well, i will let you discover it if you have some spare time.