Dealing with a Circular Dependency

tropicana picture tropicana · Mar 30, 2011 · Viewed 18.1k times · Source

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 experience with this type of problem.

Answer

jmg picture jmg · Apr 3, 2011

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?