This question is around the standard practice for implementing the MVC architecture in Java - Swing particularly. I know this question has been asked before but I want to be a bit more specific around the use of the Controller.
I've been separating my models, views, and controllers where:
- Data are processed within a model class
- Swing components are within a view class
- Event handling anonymous classes are also in the view class (user inputs)
- A controller class contains references to the model and view objects
Back to the specific of the controller - I've been using class (static) variables to represent controllers for easy access by any part of my application. So my controller classes may look like this:
public class Controller {
public static ControllerA controllerA;
public static ControllerB controllerB;
}
public class ControllerA {
private JPanel panel1;
private JPanel panel2;
private DefaultListModel list;
}
...
Every time I need to do something I would call the controller like this:
Controller.controllerA.doSomething
This means that the bulk of my code are located within the controller. Often if I need to do something, the controller would have a method for it, and it often requires an equivalent method in the view or the model to accomplish the task. I find that this leads to code duplication. For example:
Controller.controllerA.removeElement();
Will call the following method in the controller:
protected void removeElement() {
list.removeElement()
}
As my application grow, I'm seeing a lot of instances where the controller simply mirror the action required by the model or the view because it is the main access point to the view/model.
So my questions are:
- Is it a good practice to use static variable for accessing controller objects?
- Is the code duplication between controller->model and controller->view a side effect of MVC?
- Am I doing this wrong? If so, how would you implement a controller within the MVC?