Import cycle error - solutions?

Hi,

So today I received the “import cycle not allowed” compile error. I like the way Go forces you to think about your program design better., or rather how Go internals make it possible to write projects that adhere to good design principles as explained in @dfc 's excellent SOLID Go Design blog and video.

It seems the ‘import cycle not allowed’ problem is because the Dependency Inversion Principle (The “D” in SOLID) is not adhere to.

So basically I had the A depends on B, B depends on A scenario.

package router

import (
    "net"
    "project/connection"
)

type MessageRouter struct {
    connections map[net.Addr]*ClientConnection
}

package connection

import "project/router"

type ClientConnection struct {
    router *MessageRouter
}

I managed to quickly solve the problem by making the map of connections to rather use net.Conn, which is an interface:

type MessageRouter struct {
    connections map[net.Addr]*net.Conn
}

This compiled

But this made me wonder if this is really the right solution. What if I could not use net.Conn?
Should one have to create a new package with an interface type? And which of the 2 packages should then implement said interface?

Pieter

My guess is you have accidentally split your package into several. If both
packages are so tightly coupled that they need the other to work, they
should be merged.

Yeah you’re right,I did split them with the idea to decouple them,mainly to open possibility to add another map of connections (i.e say a websocket package) to the router later.

So I guess you shouldn’t always have to decouple then?

If you want to do that your map should be from a key to an interface type, not a concrete type.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.