Many students don’t know how to organize their code. Abstractions and Interfaces make a difference when developing Java applications. What if your code was divided? For instance, if you built a network application with a GUI (Graphical User Interface). The first approach is to put the code all together because it’s easier from the beginning. That’s wrong because it’s harder to find an error, and you have to read a lot of garbage code like textBox.setValue…
What about dividing this network application in two layers? One layer, with all the network code and the top layer with only the GUI? How is this possible? Using Java interfaces and the notion of events.
We can start by creating our event interface that will be waken up, when for instance we are receiving a message from the network:
public interface EventNetworkInterface {
void receiveMessage(String msg);
}
Now it’s time to build our simplified network layer:
public class NetworkLayer {
EventNetworkInterface gui = null;
public NetworkLayer(EventNetworkInterface gui) {
this.gui = gui;
}
public void receiveMessageNetwork() {
//simulates receiving a message from the network
String msg_received = "Hello World!";
//wake up event in the GUI
gui.receiveMessage(msg_received);
}
}
Now with the network layer created you have to create the GUI:
public class GUI implements EventNetworkInterface {
public static void main(String[] args) {
new GUI();
}
private NetworkLayer nl;
public GUI() {
nl = new NetworkLayer(this);
//issue a receiveMessage event:
nl.receiveMessageNetwork();
}
@Override
public void receiveMessage(String msg) {
System.out.println("I sent the message: " + msg);
}
}
In the GUI constructor we are simulating a receivedMessage event after we build the network layer and send the GUI that implements the events that will be waken up when a receiveMessage (in this case) happens.
With this approach you can separate the design code, from the processing code and simplify when you are adding more features to the layers beneath you.
If you want to have multiple classes to execute the same events, see more about the observer pattern.
