Piggy Chu
Piggy Chu

Reputation: 51

How and why interfaces will solve circular references problem?

According to this answer (and many other articles from other sites), interfaces are the solution to solve circular references, but yet none of it explained "how and why"? (except assembly issues)

Here is what I don't understand:

Say, if we add a constructor to both Foo and Bar in the linked answer as follows:

public Foo()
{
    myBar = new Bar(this);
}

public Bar(Foo foo)
{
    myFoo = foo;
}

Then how is it "not referencing each other", since we can endlessly call myBar.myFoo.myBar.myFoo... and result in a "closed loop"?

I know I shouldn't "purposely" write constructors that will reference each other, but, in most cases, circular references are created, albeit bad design, because "A class wants to know something about B class and vice versa", so it wouldn't make any sense if someone creates 2 classes that "have nothing to do with each other". If that's the case, then there are no "circular reference issues" to begin with.

So, could somebody please be so kind explaining it to me?

Upvotes: 0

Views: 252

Answers (1)

MakePeaceGreatAgain
MakePeaceGreatAgain

Reputation: 37020

You're essentially mixing two things here. One beeing a conceptual view - that is what your program does. If you have a dependency of a Foo-instance to a Bar-instance and vice versa that's absolutely fine from a class-hierarchy-view. A father knows its children, and those know there father. You can introduce interfaces for father and children, however the dependency is still there - you only resolve it at runtime instead of at compile-time. So the interface won't change that semantics at all, it only moves resolving dependencies from compile-time to runtime.

The other point here is a more technical thing - where a class is located. As long as this is the same assembly, that forementioned circular dependency is no problem at all. If those are different assemblies, the compiler will omit an error. That's where an interface will make a difference, because you resolve the actual types at runtime instead of at compile-time.

Upvotes: 1

Related Questions