views:

158

answers:

2

Hi, I am refactoring some code for an assignment - currently the view has lots of buttons and menus and one action listener which decides what to do by using event.getSource(). From what I've read people seem to think its better for each GUI component to have its own action listener, perhaps created through some kind of factory. However other than it cleaning up the code a bit what other benefits does this give - also does this not mean a lot more objects will be on the heap and could affect performance?

Thanks,

Aly

A: 

It's a tradeoff. Code with a bunch of if on the source is considered ugly, while masses of listeners can clutter your memory and have a negative effect on performance.

Given the choice, I usually go for what minimizes the amount of code I have to write, as less code usually means less opportunities for bugs.

Carl Smotricz
+1  A: 

Using separate listeners means that you should not need to perform boolean tests to determine what should be done in your listener. This has two benefits

  • First it makes the code run a bit faster.

  • Second it enhances maintainability and extendibility of your code. If you need to add a new component, you don't need to modify existing methods.

If you try to have one listener (often the applet or application object itself) act as listener for several components, then you are undoing the basic dispatch that is central to calling methods, and are implementing dispatch by hand. This requires that some sort of switch mechanism be used to distinguish the various components whose events you are handling. The system is better equipped to do this than you are. This switch structure is both error prone and difficult to maintain as the program grows. Leave the dispatching to the system.

Source: Patterns for Java Events

davidrobles