Dealing with a Circular Dependency
I wonder if someone can advise on any good ways to break a circular dependency between 2 classes in Java.FindBugs proposes the use of interfaces so i wonder if someone has any good experie开发者_Python百科nce with this type of problem.
Circular dependencies aren't always to be avoided. I'd avoid them in the large, but keeps in small tight corners of a system. In the large, i.e if data access layer and the representation layer of J2EE app circular dependent, I'd say that is a bad thing, because it means that everything has to be compiled in one go and testing is nightmare. But, it's no problem if a list data-structure and its iterator type are circular dependend.
As Findbugs suggests use interfaces to break a circular dependency. I.e introduce a interface for at least one type of the circle and make the other classes use the interface everywhere. Do you need example code?
Suggest reading about the dependency inversion principle, e.g. What is the Dependency Inversion Principle and why is it important? or http://en.wikipedia.org/wiki/Dependency_inversion_principle
There's a blog post here on how Restructure101 was used to remove cyclic dependencies, "tangles", from Junit and a presentation from the Lausanne JUG on how it was used to remove tangles from Icefaces.
As for the debate on whether cyclic dependencies are bad, I suggest reading Uncle Bob's Solid Principles.
Disclaimer: I work for Headway Software the developers of Restructure101.
精彩评论