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 Figure
s inside it, having its own Layout
, which makes package figure
dependent on package layout
.
I have though of some solutions, like creating a Container
interface which Figure
implements and putting it in the Layout
package. Is this a good solution? Any other possibilities?
Thanks
4
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.
4
I’m not too clear on what a Figure
is, but perhaps it should be in the same package as Layout
?
Your proposed Container
interface solution wouldn’t work – unless you put the Container
interface in a 3rd package then you would still have a circular dependency between the two packages. See michael_s’s answer for something which would work.
Another thing, as others have mentioned – it will probably never be an issue. You’re only going to run into problems in future if Figure
and Layout
want to be in separate modules. You can deal with this if and when that becomes necessary, but given that the two classes seem quite closely related this seems highly unlikely.
0