Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are circular dependencies considered bad design?

In my work (which is 90% Java but I'm sure this question applies to other languages) I often create two classes that "know about" each other. More concretely, class A imports B, and class B imports class A, and both have member or local variables of the other type.

Is this considered bad design? An anti-pattern if you will?

like image 762
John Fitzpatrick Avatar asked Feb 07 '12 09:02

John Fitzpatrick


People also ask

Are circular references bad?

However, from a pure design point of view, circular referencing is still a bad thing and a code smell. Circular referencing implies that the 2 objects referencing each other are tightly coupled and changes to one object may need changes in other as well. There is no one way to avoid circular reference in JS.

What is circular dependency problem?

In software engineering, a circular dependency is a relation between two or more modules which either directly or indirectly depend on each other to function properly. Such modules are also known as mutually recursive.

Are circular dependencies bad Java?

In and of themselves, circular dependencies are not a problem. However, what they point to - tight coupling - generally can be a problem. Essentially, by tightly coupling two classes you're accepting that a change in one is likely to result in a change in the other.

How do you resolve circular dependency issues?

The best solution is to avoid circular dependencies, of course, but it you're truly stuck, you can work around the issue by using property injection and RegisterInstance<T>(T t) (or its equivalent, if you're not using Autofac).


1 Answers

Here is my take:

  • If the two classes belong to the same logical module, then it's probably fine (still a judgement call of course, with lots of grey areas).
  • It's less fine if the two classes belong to different modules. This creates a circular dependency between modules. I try to avoid that as much as can, preferring a clear hierarchical structure.
like image 92
NPE Avatar answered Oct 01 '22 23:10

NPE