Is usage of anonymous classes in Java considered bad style or good? [closed]
Asked Answered
S

15

39

I know anonymous classes save typing when it comes to implementing Listener and similar stuff. They try to be a replacement for some usages of closures.

But what does the community think about the value of this language-feature? Does it make sense and do you use it regularly? Does it make the code clearer, more understandable and more maintainable? Or do anonymous classes make the code less readable?

What is your opinion, and please have examples/arguments handy to support your opinion?

Slippery answered 28/1, 2009 at 10:17 Comment(1)
Kindly refer to my answer for more clarification https://mcmap.net/q/212862/-are-inner-classes-commonly-used-in-java-are-they-quot-bad-quot-closedCrossbreed
B
31

I tend to use anonymous inner classes in situations where I don't need to have a full-blown class just to perform some task. For example, if I want to implement an ActionListener or Runnable, but I don't think having an inner class would be necessary. For example, for starting a simple Thread, using an anonymous inner class might be more readable:

public void someMethod()
{
    new Thread(new Runnable() {
        public void run()
        {
            // do stuff
        }
    }).start();
}

In certain cases, such as the example above, it can increase readability, especially for one-time tasks, as the code that is to be executed is all written in one spot. Using an inner class would "delocalize" the code:

public void someMethod()
{
    new Thread(new MyRunnable()).start();
}

// ... several methods down ... //

class MyRunnable implements Runnable
{
    public void run()
    {
        // do stuff
    }
}

That said, however, if there is going to be cases where the same thing is going to be repeated, it should indeed be a separate class, be it a regular class or an inner class.

I tend to use anonymous inner classes in programs where I am just trying things out rather than have it as a central feature of an actual application.

Bessette answered 28/1, 2009 at 10:30 Comment(0)
H
13

One more good use of anonymous inner class is when you need to initialize collections like ArrayList and Set. This practice is also known as double brace initialization For example ,

private static final Set<String> VALID_CODES = new HashSet<String>() {{
add("XZ13s");
add("AB21/X");
add("YYLEX");
add("AR2D");
}};

Obviously, this is not limited to collections; it can be used to initialize any kind of object -- for example Gui objects:

 add(new JPanel() {{
setLayout(...);
setBorder(...);
add(new JLabel(...));
add(new JSpinner(...));
}});
Harper answered 7/6, 2012 at 9:3 Comment(1)
That is really nice syntactic sugar. However, there's a price to pay for it, and that overweighs it's benefits. According to Baeldung it's considered an Anti-Pattern.Johnathanjohnathon
G
12

My opinion is anonymous classes makes the code less readable. For implementing listeners anonymous classes are useful. For developing a GWT application anonymous classes are the better choice. For these cases, if we are not using anonymous classes then the number of lines of code will increase.

Greeley answered 28/1, 2009 at 11:23 Comment(0)
G
6

We use anonymous classes regurlarly. I find them easy to use for implementing interfaces that have only one or two methods and that where the functionality isn't used anywhere else. If you use the same functionality again somewhere else there should be a real class to be reused.

Gorge answered 28/1, 2009 at 10:23 Comment(1)
Or the anonymous inner class and some of the code surrounding it moved into a separate method. Amongst other things it makes your "API" less cluttered.Rightist
S
6

Whether using anonymous class improves or degrades legibility is a matter of taste. The main issue is definitely not here.

Anonymous classes, like inner classes, carries a reference to the enclosing class, thus making non private things that without it would be. To be short, the this reference of the enclosing class may escape through the inner class. So the answer is: it is a very bad practice to use an inner class if it published itself, since that would automatically publish the enclosing class. for example:

changeManager.register(new ChangeListener() {
    public void onChange(...) {
       ...
    }});

Here, the anonymous ChangeLstener is passed to the register method of a ChangeManager. Doing so will automatically publish the enclosing class as well.

This is definitely a bad practice.

Shainashaine answered 3/1, 2011 at 12:51 Comment(0)
F
3

I use anonymous classes mostly for interfaces that have only a single method, i.e. Runnable or ActionListener. Most larger interfaces warrent their own classes or implementation in an already existing class. And as it is my opinion I don’t need arguments to support it.

Foxtail answered 28/1, 2009 at 10:23 Comment(0)
R
2

If limiting scope and access as much as possible is a good thing, then anonymous classes are very good. They are limited in scope to the one class that needs them. When that's appropriate, I'd say anonymous classes are good.

The instant you duplicate the same function, it becomes a bad idea. Refactor it into a public class that stands on its own. IDEs with refactoring features make that easy.

Rodent answered 28/1, 2009 at 13:8 Comment(1)
But private inner classes are also restricted in scope to their outer class. What makes anonymous classes better?Slippery
V
2

Anonymous class is mostly seen in GUI application specially for events handling.Anonymous class is useful in cases of implementing small interfaces that contains one or two methods..For example.. you have a class where you have two or three threads and you want to perform two or three different tasks using those threads.In this situation you can take the help of anonymous class to perform your desired tasks. look at the follow example

class AnonymousClass{

public static void main(String args[]){


    Runnable run1=new Runnable(){

        public void run(){

            System.out.println("from run1");
        }

    };
    Runnable run2=new Runnable(){

        public void run(){

            System.out.println("from run2");
        }

    };
    Runnable run3=new Runnable(){

        public void run(){

            System.out.println("from run3");
        }

    };



    Thread t1=new Thread(run1);
    Thread t2=new Thread(run2);
    Thread t3=new Thread(run3);


    t1.run();t2.run();t3.run();

}
}

output:

from run1

from run2

from run3

In the above snap of code i have used three threads to perform three different tasks. Look i have created three anonymous classes that contains the implementation of the run method to perform three different small tasks.

Victorious answered 30/11, 2012 at 4:16 Comment(0)
L
1

It makes sense to use them, but you must be aware of whats being done underneath. I only use them if I need a class to do something very specific that I don't need anywhere else.

Louvenialouver answered 28/1, 2009 at 10:22 Comment(0)
P
1

It depends what you compare them to. I'd rather have them than not have them, but then I'd rather be able to supply plain code blocks to methods like Arrays.sort() than having to explicitly create a class containing my implementation of compare().

Postprandial answered 28/1, 2009 at 10:28 Comment(0)
M
0

There is nothing inherently different or special about anonymous classes. They are ultimately just syntactical sugar with support for referencing the outer class. This makes it easier to author adapters - just like most of the Iterator implementations returned by the Collections framework.

Moorwort answered 28/1, 2009 at 10:40 Comment(1)
Referencing the outer class is also possible with normal inner classes. Anonymous classes get no classname, that's the most important difference. They can be used only once this way.Slippery
P
0

I use Anonymous classes mostly a) shorthand notation if the interface has one or two methods and it wont affect the readability

b) situation where I wont be able to justify creation of a new class, for example In swing when you have to attach an actionlistner to lets a JButton for some trivial operation.

Postulant answered 28/1, 2009 at 11:8 Comment(0)
P
0

I agree with what many others have said in that they are useful for small interfaces when only used once. But I would also add the restriction that if code external to the anonymous class has to be altered for it to work, then don't use an anonymous class.

If you have to start declaring variables as final to accommodate the anon class since it references them, then use an inner class instead. I have also seen some bad code smells where final arrays (of size 1) are used to return results from anon classes.

Pskov answered 28/1, 2009 at 15:5 Comment(0)
I
0

Anonymous classes don't "Hide" code but they do TEND to make it slightly less reusable. Note that this applies to closures as well.

In some ways they allow some nice refactors because you are allowed to pass code into a method. This can be used very effectively to reduce duplication and I'm certainly not against Anonymous classes/closures, however there are a few cases where they can be a drawback.

First consider that the anonymous inner class code you are passing in does not lend itself to reuse in your code. If you are doing the same thing in some other code you'd have to re-write it as something other than an anonymous inner class in order to reuse it and at that point it could be difficult to even know that there is code elsewhere to reuse.

Along with the lack of reuse is it's difficulty to parameterize, which leads to my biggest complaint... they tend to lead to copy and paste code.

I've seen quite a few GUIs where someone started with anonymous inner classes as event responders. Many had to do something slightly different, For instance, 5 lines of code where the only difference is a string in the middle. Once you are in the habit of using inner classes the easy solution is to copy and paste the block and replace that string.

The solution of creating a new "Named" class that has a string parameter and passing that class to all the methods rarely occurs to someone at that point. This named class can use parameters or inheritance to define different behaviors as well as code.

I'm a fan of closures and don't hate anonymous classes--just pointing out some pitfalls I've seen.

Ieyasu answered 1/5, 2017 at 16:38 Comment(0)
A
0

So with java 8 new feature of static methods in interfaces, you can use an anonymous inner class to return an instance of your interface. For example:

interface Person {
 String getName();
 int getAge();

 static Person newInstance() {
   return new Person() {
     public String getName() {
        return "Bob";
     }

     public int getAge() {
        return 99;
     }
   } 
 }
}

And you can get an instance like so:

Person person = Person.newInstance();

Basically this allows for a single default implementation of your interface.

Autolithography answered 5/12, 2020 at 22:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.