I’m a self-taught programmer, and like many other noobs I once struggled with the classic “passing data between forms” problem. When I was building my first chat application in Java around a year ago, I came across this problem again. I solved it by passing a reference to the running GUI to the constructor of another class so it could directly manipulate the GUI. For example:
class GUI {
Writer w;
void initGUI() {
w = new Writer(this);
}
}
class Writer {
GUI ui;
public Writer(GUI ui) {
this.ui = ui;
ui.textBox.write("Yo");
// now, instead of the "this" keyword, I can say "ui.w" or "ui.w.ui.w.ui.w..."
}
}
I am certain that this is one of the most efficient ways to transfer data “upstream”, but I was given grief (and some praise) for suggesting this on a forum for someone having the same problem. So what kind of chaos could arise from doing this on larger applications? When I look at my applications that use this, I notice that they’re very pragmatic and efficient, but also a bit too organic (if you will) and complicated (especially when there are threads accessing the GUI at different times, etc).
Is there a better way of doing this? I took a different approach out of necessity while using Qt, but it was more complicated since it used signals, slots, and threading. Please point me in the right direction. Thanks.
The main problem with this approach is coupling. The Writer class, instead of being a generic, reusable Writer class, able to do its job and, if needed, send events about what it does, is tightly coupled to this specific GUI.
If it accepted listeners, like all the Swing components do, you could reuse the Writer in several different GUIs, or choose to update a text area instead of a text field for example.
Another solution would be touse pull rather than push. Instead of having the writer update the GUI, you could have the GUI call methods of the writer in order to query its state. It’s not always possible, but it often is.