Friday, April 01, 2005

SWT/JFace, MVC, JUnit

Whew! Did I get them all in there? I have been struggling lately with the Model-View-Controller pattern. Well, I haven't been struggling with the pattern itself as much as I had been struggling with how to implement it properly and create unit tests in an SWT/JFace application. Being new to MVC, one struggles with what should be in the controller and what should not. I was trying to put everything in the controller, but that is not always feasible.

In my case, I was unsure about the inherited methods from the JFace Window class, such as createContents(), initializeBounds(), etc. Well, those methods do not need to be in the controller, because there is no interaction with the model. These methods are strictly there to create and initialize the view. The methods that I ended up putting in the controller were only those that dealt with the view with respect to the model.

For instance, in my example application that I put together tonight to play around with this process, I have a Contact class (model), a setup dialog (view), and a controller class. The model contains nothing more than first, middle, and last name strings for this example. It is quite simple. The view is also simple in that it has three Label controls, three Text controls, and two Button controls (Print and Cancel).

My controller class ended up having the following methods:

public void onFirstNameChanged();
public void onMiddleNameChanged();
public void onLastNameChanged();
public void onPrintClick();
public void onCancelClick();
The first three methods are called in the focusLost method for the FocusListener on the respective edit control for each component of the contact name. The onPrintClick method is called when I click on the Print button. It fires the print method on the view and does nothing more than print the contents of the model out to the console in this simple example. The onCancelClick method fires the close method on the view.

I was able to create unit tests for my controller class and the model, but I did not really create anything for the view. The view does nothing more than initialize itself and wait for user input or receives events from the controller. Since all of the major work for updating the model and other user interaction is handled in the controller, then I am not even sure if it matters that there are no unit tests for the view.

I could have simplified this example a little more by combining the view and the model, but since I have most of the classes already created for an application that I am currently working on for myself, I figured I would see if I could get things working with a model that is separate from the view.

I came across an interesting discussion on Martin Fowler's web site tonight which talks about Model-View-Presenter.  I need to investigate this further.

Technorati Tags: , , , , , , , ,

No comments: