Home arrow static arrow Java Programming [Archive] - Anonymous class replacement
Warning: Creating default object from empty value in /www/htdocs/w008deb8/wiki/components/com_staticxt/staticxt.php on line 51
Java Programming [Archive] - Anonymous class replacement
This topic has 11 replies on 1 page.

Posts:13
Registered: 8/1/04
Anonymous class replacement  
Aug 2, 2004 12:40 AM



 
I wonder if there are any thoughts on the following technique. I have a real distaste for anonymous classes; while I understand the convenience, nothing can blow up a nice compact method like a bunch of braces. So I have come up with the following:

public class Utility
{
public static ActionListener createActionListener(Object target, String method)
{
Class c = target.getClass();
ActionListener result = null;
try
{
final Method action = c.getMethod(method, null);
result = new ActionListener() {
public void actionPerformed(ActionEvent arg0)
{
try
{
action.invoke(target, null);
}
catch (Exception e)
{}
}
};
}
catch (Exception e)
{}
return result;
}

So essentially I am using relection as a replacement for C's function pointers. While the above class is somewhat convoluted, I only write it once, and then I do, e.g.

JButton button = new JButton("Push me");
button.addActionListener(Utility.createActionListener(this, "buttonPushed"));

which isn't perfect, but which I like better than creating the anonymous class. I understand that in this code I am ignoring the ActionEvent; I plan to dig a little deeper into reflection to test whether the method ("buttonPushed" in this case) takes such a parameter, and pass it along if it does. Often the parameter is ignored, so that's what I did in my first attempt.

Any thoughts?
 

Posts:12,831
Registered: 2/22/00
Re: Anonymous class replacement  
Aug 2, 2004 1:07 AM (reply 1 of 11)



 
It's too bad that you don't like anonymous classes, because they're great, and they make code cleaner. And you don't even get any extra braces; I'm not sure what you meant by that. I guess the braces are closer together. (Hope you'll never have to code LISP or you'll get an aneurism.) Actually it looks like you have more braces with your solution anyway.

And you didn't actually get rid of any anonymous classes; you just moved it into a sort of factory.

And if you worked for me and you came up with a convoluted way to use reflection to fool yourself into thinking that you're not using a useful language feature because you feel that you don't like said feature, I'd fire you.

And you're catching Exception silently. More grounds for dismissal.

You asked for thoughts. Sorry if you don't feel they're nice.
 

Posts:13
Registered: 8/1/04
Re: Anonymous class replacement  
Aug 2, 2004 1:24 AM (reply 2 of 11)



 
Well, I said it's a first attempt, I didn't say it's a polished example. And if you can't see that using anonymous classes introduces braces, I wouldn't be working for you in the first place. It's frankly irrelevant how complicated the setup method is, because as I said before it gets written only once.

In case you missed the point; to use an in-line anonymous class requires something like

button.addActionListener( new ActionListener()
{
public static void actionPerformed(ActionEvent e)
{
// call the method I really want to call, say it's buttonPushed
this.buttonPushed();
}
});

That is a ridiculous amount of code to set the action of a button. My method requires only

button.addActionListener(Utility.createActionListener(this, "buttonPushed"));

if you can't see that the second way is more compact AND more readable, then like I said, I wouldn't be working for you.

Now, there are some drawbacks to the second method--for example, reflection seems like a heavy-handed approach to the issue. If anyone has some comments on the pros and cons of the actual technique, rather than who they would fire, I'd like to hear them.
 

Posts:81
Registered: 6/9/04
Re: Anonymous class replacement  
Aug 2, 2004 1:40 AM (reply 3 of 11)



 
The inner class doesnt have to be anonymous. Thats what I always do. I dont know if its good or bad but it works for me. Theres no more and no less overhead if you name it.

For example
class Foo extends JFrame{      class WindowExit extends WindowAdapter{             public void windowClosing(...){//cean up then System.exit(0);}       }       Foo(){ addWindowListener(new WindowExit());}}


You could do the same thing with a buttonlistener. Remember an inner class isnt static and has the ability to manipulate its parents data so theres no need for a second call to the parent.

Im a java noob though but I found anon classes in the middle of functions to be bulky. I found naming them as inner classes worked for me just fine. Not sure if its "professional"
 

Posts:2,830
Registered: 9/1/03
Re: Anonymous class replacement  
Aug 2, 2004 1:44 AM (reply 4 of 11)



 
I don't like it either, but then again I don't really use anonymous inner classes
much either (at least for Listeners), I just created a simple class that extended
the appropriate listener and used that...
 

Posts:2,909
Registered: 13.8.2003
Re: Anonymous class replacement  
Aug 2, 2004 1:52 AM (reply 5 of 11)



 
I'd work for paulcw because he seems like just the kind of arrogant ***** I feel kinship to ;)
 

Posts:2,909
Registered: 13.8.2003
Re: Anonymous class replacement  
Aug 2, 2004 1:52 AM (reply 6 of 11)



 
*****! I pricked my finger
 

Posts:3,081
Registered: 2/15/99
Re: Anonymous class replacement  
Aug 2, 2004 1:52 AM (reply 7 of 11)



 
To quote page 1 of the [url=http://java.sun.com/docs/books/tutorial/reflect/index.html]Reflection API Tutorial[/url]:

First, a note of caution. Don't use the reflection API when other tools more natural to the Java programming language would suffice. For example, if you are in the habit of using function pointers in another language, you might be tempted to use the Method objects of the reflection API in the same way. Resist the temptation! Your program will be easier to debug and maintain if you don't use Method objects. Instead, you should define an interface, and then implement it in the classes that perform the needed action.
 

Posts:2,909
Registered: 13.8.2003
Re: Anonymous class replacement  
Aug 2, 2004 1:52 AM (reply 8 of 11)



 
Disregard!
 

Posts:12,831
Registered: 2/22/00
Re: Anonymous class replacement  
Aug 2, 2004 4:19 AM (reply 9 of 11)



 
If you used K&R formatting (1TBS, I think they call it), it's only 4 extra lines, with the advantage being that the code is right there as opposed to being in a wholly other class.

Another disadvantage is that by using a string and reflection to invoke the method, if there's a bug (say a typo in the method name) it won't manifest itself until run-time, whereas a normal anonymous class would show such a problem at compile time. This isn't necessarily a bad thing, but by throwing strong typing out the window it largely misses the point of using Java in the first place.

This design has one factory for each type of listener. I suppose you could extend it by making the factory-created object implement every **** interface that's likely to turn up in practice, or maybe you could work out something more flexible using (yet more) reflection. In any event if you need to use a variety of different listeners (which is usually the case in my experience), code bloat would be a problem.

continued...
 

Posts:12,831
Registered: 2/22/00
Re: Anonymous class replacement  
Aug 2, 2004 4:21 AM (reply 10 of 11)



 
Furthermore, the design only applies if each listener is only going to invoke a single method on an object that you already have a reference to.

I could see doing something like this if you had a lot of the same listeners (I mean, all implementing the same listener interface) that all fit the restrictions the design has, but that seems a relatively unlikely scenario.

Also note that if all the listeners invoked a single method on the current object (i.e., this), then you could just make the current object implement that listener, and do a lot of this:
someButton.addActionListener(this);

which is even less code.

So generally I think you have a relatively complicated unnecessary solution to something that's not really a problem except perhaps in very limited cases.

BTW, I'd also fire you for poor communication skills (can't you at least wrap your code in [code][/code] tags?) and an inability to accept criticism.
 

Posts:12,831
Registered: 2/22/00
Re: Anonymous class replacement  
Aug 2, 2004 4:55 AM (reply 11 of 11)



 

I was being silly saying that I'd fire you, but seriously, this seems like the kind of thing that we programmers find interesting to do, but is actually of limited efficacy and takes a fair amount of effort to really get right -- effort that would be better spent on whatever the real task at hand is.

Also you'd have to consider not only the effort that you put into it writing it, but also the effort of everyone else who has to maintain your code, the effort they spend hunting down the additional source, reading it, figuring out how it works, etc. Sure, presumably they'll be smart people who are capable of figuring it out (ideally -- although in practice there is no end of underqualified coders out there), but in the real world they'll have a hundred other things to do and will curse your name for being too **** clever for your own good and making them spend more time on this than they had hoped.

I'm not a big XP'er, but this is exactly the kind of thing the practice hopes to avoid...big solutions for minor problems.
 
This topic has 11 replies on 1 page.