Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: where should I put anonymous listener logic code?

we had a debate at work about what is the best practice for using listeners in java: whether listener logic should stay in the anonymous class, or it should be in a separate method, for example:

button.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        // code here
    }
});

or

button.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        buttonPressed();
    }
});

private void buttonPressed() {
    // code here
}

which is the recommended way in terms of readability and maintainability? I prefer to keep the code inside the listener and only if gets too large, make it an inner class. Here I assume that the code is not duplicated anywhere else.

Thank you.

like image 795
Denis Tulskiy Avatar asked Jan 15 '11 19:01

Denis Tulskiy


People also ask

Where do we use anonymous class in Java?

Anonymous classes enable you to make your code more concise. They enable you to declare and instantiate a class at the same time. They are like local classes except that they do not have a name. Use them if you need to use a local class only once.

Where can you use an anonymous inner class?

An anonymous inner class can be useful when making an instance of an object with certain “extras” such as overriding methods of a class or interface, without having to actually subclass a class. Tip: Anonymous inner classes are useful in writing implementation classes for listener interfaces in graphics programming.

How do you call an anonymous class in Java?

Object = new Example() { public void display() { System. out. println("Anonymous class overrides the method display()."); } }; Here, an object of the anonymous class is created dynamically when we need to override the display() method.


1 Answers

My self-imposed rule is:

  1. If the listener has more than 2 methods, create a named class.
  2. If the listener spans more than 10 lines, create a named class.

Pretty simple, easy to follow and produces more or less readable code. But then I have to admit that I never even thought of what your example shows.

like image 69
biziclop Avatar answered Sep 19 '22 02:09

biziclop