Listener styles

I remembered the first time I wrote a desktop form using java. I wrote everything inside a class, including the listeners, and the whole business process involving database access, data manipulation and so on. I didn’t realized that it’s a worst thing to do until my code gone beyond 1000 lines.

Picked a lesson from that, I begin to separate business process, data models, and user interface into something they called MVC. Upon trial and error, I came into a few style to create a desktop form:

  1. A view with one or more listeners as controllers.
  2. A view with one or more action classes as controllers connected by anonymous listeners.
  3. A view with one or more action classes as controllers accessed by private methods connected by listeners.

The first style looks like this :

Button a = new Button();
a.addListener(new AListener());

.
.
class AListener extends SelectionAdapter
{
    //extends methods and do all business process here
}

I found this style not flexible because in a large application, you might want to create more than one way to do something. A simple example is creating a button and a menu item to do the exact thing.

The second style looks like this :

Button a = new Button();
a.addListener(new Listener()
{
    AnAction x = new AnAction();
    x.run();
};

.
.
class An Action extends Action()
{
    public void run()
    {
       //do business process here
    }
}

I think this style is better than the first one, since the style allows me to put the action in any listener. But it still has a problem. Sometimes we want to modify the content of form element, say, a text field, or variable upon doing the business process. Our code become ugly because we have to put final keyword to variables we need to access inside the Listener class.

So, in order to cure the problem, I used this style :

Button a = new Button();
a.addListener(new Listener()
{
    doThings();
};

//we can access variables without using final keyword
private void doThings()
{
    AnAction x = new AnAction();
    x.run();  
}
.
.
class An Action extends Action()
{
    public void run()
    {
       //do business process here
    }
}

I think the last style is the best so far.

powered by performancing firefox

Advertisements

No comments yet

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: