Question

Best explained my the small snippet - below. Here we have two classes Math and SolveEquation. They both rely on each other. Is it conventional practice ? or an Anti-pattern that should be avoided at all costs ?

Note : please refrain alternate solutions. This example was tailor made to answer the doubt I have. Thanks.

Eg:

class SolveEquation {
   public static int solveEquation(int x, int y) {
      return Math.add(x, y)  + Math.sub(x, y);
   }
}


class Math {
    public static int solveEquation(int x, int y) {
        return SolveEquation.solveEquation(x, y);
    } 

    public static int add(int x, int y) {
        return x + y;
    }

   public static int sub(int x, int y) {
        return x - y;
    }
}
Was it helpful?

Solution

This situation is called a Circular Dependency, and yes you should avoid it. At least if you know you can avoid them, do it.

edit: There are many reasons to why you should avoid them.

The first one is that some languages (If I remember that has already happened to me in C#), you won't be able build modules with circular dependencies. (whoops)

The second one is that it tells me that the quality of the code can be better. Why? Because it usually shows signs of tight coupling, which makes your code less re-usable.

Also, in your example, it's not the case (because you used static methods), but when you want to create those objects, it'll be hard. Especially if you're using dependency injection.

More reasons are listed here

Circular dependencies can cause many unwanted effects in software programs. Most problematic from a software design point of view is the tight coupling of the mutually dependent modules which reduces or makes impossible the separate re-use of a single module.

Circular dependencies can cause a domino effect when a small local change in one module spreads into other modules and has unwanted global effects (program errors, compile errors). Circular dependencies can also result in infinite recursions or other unexpected failures.

Circular dependencies may also cause memory leaks by preventing certain very primitive automatic garbage collectors (those that use reference counting) from deallocating unused objects.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top