Java – Cyclic dependency in this project design

designjavajava8object-oriented-design

I have 2 modules (containing multiple classes). Let's call them Module A and Module B. Module B has a dependency on Module A: Module B -> Module A. Now, I have created an utility class C, which A and B are supposed to use but the utility itself depends on functionality found in A and B, thus A and B also depend on C. So something like this: C <-> B -> A <-> C.

Unfortunately, I am not allowed to extract the dependency from A and B and put them somewhere else, so they have to remain untouched (except for code using the utility). Making the utility an Interface and implementing it in A and B also does not work because the implementations would also depend on A and B respectively causing again a cyclic dependency…

Is this a general design issue of how my project is designed which is unsolvable?

EDIT: adding a bit more of details.

The dependencies are in form of method calls to classes located inside the modules A and B. An extraction would be possible but it would break the initial design and also make it look weird as it makes sense to keep them where they are.

Best Answer

If C is an utility class to be reused from A and B, it should not contain any direct dependencies from A and B. That is as simple as it is.

However, if C needs a service from A (or B) to fulfill its purpose, you should define an interface for that service, make A (and/or B) implement that interface, and inject the service into C during construction:

   class C
   {
        IService _service;
        C(IService x)
        {
            _service=x;
        }
   }

   class A : implements IService
   {
       C c;
       A()
       {
           c=new C(this);
       }
   }

This way, there will be no need to extract anything from A or B into another place, you just allow C to access the functionality in A or B through the IService interface.