Reputation: 1067
I have got a MVC structure where Im setting the color of a JPanel in a JPanel-class. I wonder which of the two alternatives is the best solution.
Alternative 2 sounds as a better solution to me but don’t know if it there is a big difference since both are working so if thats the case, why?
Thanks a lot!
ALTERNATIVE 1:
controller class
In running thread:
theView.getPanelClass().getPanel().setBackground(new Color(255));
View class
private final PanelClass panel = new PanelClass();
public PanelClass getPanelClass() {
return panel;
}
Panel class (declared in theView)
JPanel thePanel = new JPanel();
public JPanel getPanel() {
return thePanel;
}
ALTERNATIVE 2:
Controller class In running thread:
theView.setPanel(new Color(255));
View class
private final PanelClass panel = new PanelClass();
public void setPanel(Color col) {
panel.setThePanel(col);
}
Panel class (declared in theView)
JPanel thePanel = new JPanel();
public void setThePanel(Color c) {
thePanel.setBackground(c);
}
UPDATE I have now edited my code as follows so the view class are setting the color through the JPanel class.
ALTERNATIVE 3:
Controller class In running thread:
if(x>y) {
theView.setPanel(1);
} else {
theView.setPanel(2);
}
View class
private final PanelClass panel = new PanelClass();
public void setPanel(int n) {
panel.setThePanel(n);
}
Panel class (declared in theView)
public void setThePanel(int n) {
switch (n) {
case 1:
panelS1.setBackground(new Color(255));
break;
case 2:
panelS1.setBackground(new Color(0));
break;
}
}
Upvotes: 0
Views: 485
Reputation: 162
First alternative seems to violate so called Hollywood principle. I'd rather choose second alternative
Upvotes: 1
Reputation: 21522
It's a contractual decision. If you agree that this is the developer's responsibility to know the internals of your view, and that it is acceptable that he knows about getPanelClass()
and getPanel()
prior to setting the background color, then this solution (1) is viable.
If you believe it is abusive to expect programmers to know the implementation details then you'd better go with (2).
Now, there's probably a reason to it, but why are you setting the color from the controller? Shouldn't it be a decision purely made by the view itself anyway? The whole purpose of separating the view from the controller is precisely to not interfere in this kind of decisions. What if you decide to update the view in x years with another component, are you certain it will have a background color setter as well? If so, make sure your current view implements an "ViewWithBackgroundColorSetter" interface for example.
You see I'm expanding a bit but your issue delves deeper than you may think.
Upvotes: 1