First I will present a quick outline of a somewhat tightly coupled classes (though not the worst possible case):
class setUpGUI {
...
JTextField output = new JTextField();
...
CountTimer ct;
...
public void setOtputText(String text) {
output.setText(text);
public startTimer() {
ct = new CountTimer();
}
...
}
class CountTimer implements ActionListener {
private String text = "";
private gui = new SetUpGUI();
...
@Override
public void actionPerformed(ActionEvent e) {
...
gui.setOtputText(text);
...
}
My question is about the second snippet (in comparison with the first and on its own):
// functionally equivalent to com.google.gwt.user.client.ui.HasText
interface HasText {
String getText();
void setText(String text);
}
class setUpGUI {
...
JTextField output = new JTextField();
...
CountTimer ct;
...
public void setOtputText(String text) {
output.setText(text);
public startTimer() {
ct = new CountTimer(output);
}
...
}
class CountTimer implements ActionListener {
private String text = "";
private HasText txtComp;
...
CountTimer(txtComp) {
...
this.txtComp = txtComp;
...
}
@Override
public void actionPerformed(ActionEvent e) {
...
txtComp.setText(text);
...
}
}
I believe that the second design can be considered a loose coupling, since instead of using a setter
it passes a reference through constructor and at the same time defines its own HasText
interface (since Swing does not seem to have one and I didn't find a common parent of JtextComponent
and JLabel
that has setText()
method). Would you agree?
What is the general attitude towards passing a parameter via constructor?