How to solve circular reference?

user145610 picture user145610 · Aug 3, 2011 · Viewed 49.5k times · Source

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?

Answer

Ed Bayiates picture Ed Bayiates · Aug 3, 2011

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.