Friday, November 28, 2008

Update: Random Staffer

Hey, peeps! I hope everyone had a good Gobble-Gobble-fest yesterday! Anyways, on to business.

Random Staffer is coming along nicely. However, I ran into something I really didnt like yesterday. In order to handle events on a form element (say, a button or menu item click), you need to use an ActionListener. There are two ways to do this effectively. The first, and seemingly most popular, method is to declare your class as extending the ActionListener class. This means you can point to this class as your listener, then add the ActionPerformed method to your class definition. This presents an issue of redundancy. For example, if you have some buttons and your class set up in the above fashion, you would need to add the action to take when the buttons are clicked separate from the button instantiations and set-up. This creates a readability nightmare, where if you want to know what happens when you click Button1, you would have to track it down in the ActionPerformed method further in the code.

The second method is to take advantage of Java's ability to change non-static method definitions at run-time. This means you can create a new instance of an ActonListener, and set the ActionPerformed method for that specific instance. This is great because you have resolved the redundancy and readability issues by including everything for the respective button in as little as two lines. However, this comes with the price of a new class file being generated for each time you do this, quickly changing a two-file project into a 20-file project. This happens because Java needs to create a completely new definition of the ActionListener class since the original has been changed.

Apparently, the desired effect is to have low-to-no redundancy, while eliminating the need for multiple class files. My proposal was to take advantage of Java's Class and Method classes. These provide your program with the ability to take in references to methods in other classes and call them dynamically. The problem I didnt forsee was that this only works on public and protected methods, which means every method that needs to be called when a button is pressed now has the potential to be called from the dangerous outside world. So, now its back to the drawing board.

No comments: