I know circular dependency is considered to be a design issue, but what if it's not possible to redesign the program, Is it a bad practice to solve it with events?
For example, let's say I have two classes I want to call methodB from ClassA and methodA from ClassB.
The solution looks like this:
class ClassA {
classB: ClassB;
constructor() {
this.classB = new ClassB();
this.classB.methodB();
this.classB.eventEmitter.on('callMethodA', (data) => {
this.methodA(data);
});
}
methodA(data) {
console.log(data);
}
}
class ClassB {
eventEmitter: EventEmitter;
constructor() {
this.eventEmitter = new events.EventEmitter();
this.eventEmitter.emit('callMethodA', 'some data');
}
methodB() {
console.log("hello");
}
}
There are 2 downsides I can think of:
ClassB can't get the return value from methods in ClassA.ClassA must be Singelton to avoid duplicate listeners.Is it considered to be a bad practice? What are the alternatives?