Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to solve circular reference?

How do you solve circular reference problems like Class A has class B as one of its properties, while Class B has Class A as one of its properties?

How to do architect for those kind of problems?

If you take an example of NHibernate, there will be a parent-child relationship between objects.

How is it able to handle those parent child scenarios?

like image 515
user145610 Avatar asked Aug 03 '11 14:08

user145610


People also ask

Why am I getting a circular reference in Excel?

The circular reference error message "There are one or more circular references where a formula refers to its own cell either directly or indirectly. This might cause them to calculate incorrectly. Try removing or changing these references, or moving the formulas to different cells."

How do I stop circular reference warning in Excel?

On the 'Excel Options' window, go to the 'Formulas' section and tick the 'Enable iterative calculation' box. Click 'OK' to save the changes. After that, you will not get any warning whenever there's a circular reference.

What is a circular reference example?

A circular reference is a type of pop-up or warning displayed by Excel that we are using a circular reference in our formula and the calculation might be incorrect. For example, in cell A1, if we write a formula =A1*2, this is a circular reference as inside the cell A1 we used the cell reference to A1 itself.


2 Answers

In most cases when I've had to have two things reference each other, I've created an interface to remove the circular reference. For example:

BEFORE

public class Foo {     Bar myBar; }  public class Bar {     Foo myFoo; } 

Dependency graph:

Foo     Bar  ^       ^  |       | Bar     Foo 

Foo depends on Bar, but Bar also depends on Foo. If they are in separate assemblies, you will have problems building, particularly if you do a clean rebuild.

AFTER

public interface IBar { }  public class Foo {     IBar myBar; }  public class Bar : IBar {     Foo myFoo; } 

Dependency graph:

Foo, IBar     IBar     ^          ^     |          |    Bar        Foo 

Both Foo and Bar depend on IBar. There is no circular dependency, and if IBar is placed in its own assembly, Foo and Bar being in separate assemblies will no longer be an issue.

like image 88
Ed Bayiates Avatar answered Sep 22 '22 15:09

Ed Bayiates


I would tell your friend he needs to rethink his design. Circular references like you describe are often a code smell of a design flaw.

like image 33
John Kraft Avatar answered Sep 25 '22 15:09

John Kraft