Java – How to Solve Circular Package Dependencies

Architecturejavapackages

I am refactoring a large codebase where most of the classes are located in one package. For better modularity, I am creating subpackages for each functionality.

I remember learning somewhere that a package dependency graph should not have loops, but I don't know how to solve the following problem: Figure is in package figure, Layout is in package layout, Layout requires the figure to perform layout, so package layout depends on package figure. But on the other hand, a Figure can contain other Figures inside it, having its own Layout, which makes package figure dependent on package layout.

I have though of some solutions, like creating a Containerinterface which Figure implements and putting it in the Layout package. Is this a good solution? Any other possibilities?

Thanks

Best Answer

You should think about Inversion of Control

You basically define an interface for your Layout which is located somewhere near your Layout class in an own package so you would have an implementation package and a public interface package - for instance call it Layoutable (I don't know if that's proper English). Now - Layout won't implement that interface but the Figure class. Likewise you would create an interface for Figure that's Drawable for instance.

So

my.public.package.Layoutable
my.implementation.package.Layout
my.public.package.Drawable
my.implementation.package.Figure

Now - Figure implements Layoutable and thus can be used by Layout and (I'm not sure yet if that is what you wanted) - Layout implements Drawable and can be drawn in a Figure. The point is, that the class that exposes some service makes it available by an interface (here: Layout and Layoutable) - the class that wants to use that service has to implement the interface.

Then you would have something like a creator object that binds both together. So the creator would have a dependency to Layout as well as to Figure, but Layout and Figure themselves would be independent.

That's the rough idea.

An excellent source for solutions to this problems is the book Java Application Architecture by Kirk Knoernschild.