I have read up on dependency injection and interfaces, but I am still confused about the best way to decouple packages in my situation. Say I have a UIClass in UIPackage:
package UIPackage;
import NetworkPackage.NetworkClass
class UIClass() {
public static void displayMessage(String message) {
// show the message on screen
}
private static void messageEntered(String message) {
NetworkClass.sendMessage(message);
}
}
and a NetworkClass in NetworkPackage:
package NetworkPackage;
import UIPackage.UIClass;
class NetworkClass() {
public static void sendMessage(String message) {
// send the message to the network
}
private static void messageReceived(String message) {
UIClass.displayMessage(message)
}
}
These packages depend on each other, but I would like to have the network package work independently of the UI package to remove the dependency cycle. The only way I have found to do that so far is to create an interface for the UIClass to implement (UIInterface), and then an instance of UIInterface is passed to the NetworkController in the constructor or something. This seems like it just makes things more complicated though as that interface would need to be in its own package which is then included in both of the original packages.
Should I create a third package for interfaces of this type? Should I just leave the circular dependency and not worry about it?
Clarification 1
This is not the code I am actually using, I just named the packages that way so that the example would be clearer. The app uses multiple threads, which is why NetworkClass
needs a references to UIClass
, because it is constantly waiting for a new message while the UI may be doing other things on a different thread. When a message is received, it needs to be able to update the UI and display the message. These packages have many other classes that do other things, but for the sake of example these classes are all that is exposed.