user5636236
user5636236

Reputation: 387

Circular dependency between modules java classes

I have two modules: UI and Core. In the last one resides the business processing logic. In my first implementation, the UI module has dependencies on the Core module.

But now I have implemented websockets in the UI module for Core to send a message to UI/websocket to update UI about status changes.

We have a Handler class in UI module which can send the message to UI-websocket. My issue is: How do I access that Handler class in Core to send message to websocket?

Upvotes: 1

Views: 4880

Answers (2)

Solomon Slow
Solomon Slow

Reputation: 27190

Module A can call in to module B without depending on module B if it defines an interface, and if it provides a method that module B can call to pass in a callback object that implements the interface.


Suppose I've defined the Foobar library, and suppose that the status of the Foobar library could change because of some external event. If the library client wants to be aware of status changes, I could provide a callback mechanism:

interface StatusCallback {
    void statusChange(Status status);
}

class Foobar {
    ...
    void registerStatusCallback(StatusCallback statusCallback);
    ...
}

The client uses it by creating an instance that implments StatusCallback, providing it to the library:

Foobar foobar = ...;

statusCallback = new StatusCallback() {
    void statusChange(Status status) {
         ...do something with changed status...
    }
};

foobar.registerStatusCallback(statusCallback);

Now, whenever the external event happens and the status changes, the library will call the client's statusChange(status) method. But the library source code has no dependency on the client code.

Upvotes: 1

Duloren
Duloren

Reputation: 2711

In order to resolve circular dependencies, you should move the common dependencies to another new package and make the two original packages depends just upon on the new one. For instance you could to move the websocket classes to a new package. Also consider to use the transfer object pattern.

Upvotes: 3

Related Questions