I've been reading different answers here about solving the circular dependency in software design and I still can't get it. Please help me understand it.
Let's say I have class A and class B which call methods of each other:
class A {
public:
void Do1() {
B b;
b.Do1();
}
void Do2() {
//do something
}
};
class B {
public:
void Do1() {
//do something
}
void Do2() {
A a;
a.Do2();
}
};
Classes are perfectly divided according to Single responsibility principle.
It looks like I can't apply Dependency Inversion Principle here as I can aggregate only one class into another.
According to best design practices could you suggest me the proper way on how to handle this?
I'd appreciate your answers with some code.
You need to remove the circular dependency by put them into another class. From high level, the circular dependency is one of the many ways two classes can interact with each other. The proper way to do is make them loosely couple with each other by keeping them away from interacting with each other explicitly, this let you to vary the classes independently. please check out mediator pattern. In the following example, class C is a logical mediator.
class A {
public:
void Do2() {
//do something
}
};
class B {
public:
void Do1() {
//do something
}
};
class C
{
private A a;
private B b;
C(A a, B b)
{
this.a = a; this.b = b;
}
public void A_do1 { b.do1(); }
public void B_do2 { a.do2(); }
}