Is using anonymous classes in Java a recognized bad style or good?

I know that anonymous classes preserve text input when it comes to implementing Listener and similar stuff. They are trying to replace some closing methods.

But what does the community think about the value of this language function? Does that make sense and do you use it regularly? Does this make the code more understandable, understandable, and easier to maintain? Or do anonymous classes make the code less readable?

What is your opinion and please attach examples / arguments to support your opinion?

+32
java coding-style anonymous-class
Jan 28 '09 at 10:17
source share
14 answers

I tend to use anonymous inner classes in situations where I don't need to have a full-blown class in order to complete some kind of task. For example, if I want to implement an ActionListener or Runnable , but I don't think that an inner class is needed. For example, to run 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 some cases, such as the example above, it can improve readability, especially for one-time tasks, since the code that needs to be executed is written in one place. Using the inner class delocalizes the code:

 public void someMethod() { new Thread(new MyRunnable()).start(); } // ... several methods down ... // class MyRunnable implements Runnable { public void run() { // do stuff } } 

However, if there are cases when the same thing will be repeated, it should be a separate class, whether it be a regular class or an inner class.

I prefer to use anonymous inner classes in programs where I'm just trying to do something, rather than as the central function of a real application.

+28
Jan 28 '09 at 10:30
source share

Another good use of an 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 object - for example, Gui objects:

  add(new JPanel() {{ setLayout(...); setBorder(...); add(new JLabel(...)); add(new JSpinner(...)); }}); 
+13
Jun 07 2018-12-12T00: 00Z
source share

My opinion of anonymous classes makes the code less readable. Anonymous classes are useful for implementing listeners. For developing GWT, anonymous classes are the best choice. For these cases, if we do not use anonymous classes, the number of lines of code will increase.

+11
Jan 28 '09 at 11:23
source share

We regularly use anonymous classes. I find them easy to use for implementing interfaces that have only one or two methods and that where functionality is not used anywhere else. If you reuse the same functionality somewhere else, a real class must exist for reuse.

+6
Jan 28 '09 at 10:23
source share

I use anonymous classes mainly for interfaces that have only one method, i.e. Runnable or ActionListener . Most larger interfaces protect their own classes or implementations in an existing class. And, as it seems to me, I don’t need arguments to support him.

+3
Jan 28 '09 at 10:23
source share

If using an anonymous class improves or degrades readability, it's a matter of taste. The main question is definitely not here.

Anonymous classes, such as inner classes, contain a reference to the enclosing class, thereby doing non-private things that would not exist without it. In short, the this reference of the enclosing class may exit the inner class. So the answer is this: it is very bad practice to use an inner class if it has published itself, as this will automatically publish the enclosing class. eg:

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

Here the anonymous ChangeLstener is passed to the register ChangeManager method. This will also automatically publish the wrapper class.

This is definitely bad practice.

+3
Jan 03 2018-11-12T00:
source share

An anonymous class is mainly considered in the GUI application specifically for handling events. An anonymous class is useful when implementing small interfaces containing one or two methods. For example .. you have a class in which you have two or three threads and you want to perform two or three different tasks using these threads. In this situation, you can use an anonymous class to perform your desired tasks. see the following 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(); } } 

exit:

from run1

from run2

from run3

In the code link above, I used three threads to perform three different tasks. See that I created three anonymous classes that contain an implementation of the run method to perform three different small tasks.

+2
Nov 30 '12 at 4:16
source share

It makes sense to use them, but you should know what is being done under it. I only use them if I need a class to do something very specific that I no longer need.

+1
Jan 28 '09 at 10:22
source share

It depends on what you are comparing them to. I would rather have them than not have them, but then I'd rather provide simple blocks of code to methods like Arrays.sort (), rather than explicitly creating a class containing my implementation of compare ().

+1
Jan 28 '09 at 10:28
source share

If volume limitation and access as much as possible is good, then anonymous classes are very good. They are limited in scope to the one class they need. When appropriate, I would say that anonymous classes are good.

The moment you duplicate the same function, this becomes a bad idea. Reorganize it into an open class that stands on its own. IDEs with refactoring features make this easier.

+1
Jan 28 '09 at 13:08
source share

There is nothing special or special about anonymous classes. It is ultimately just syntactic sugar with support for referencing an external class. This simplifies the creation of adapters - like most Iterator implementations returned by the collection structure.

0
Jan 28 '09 at 10:40
source share

I use only anonymous classes a) an abbreviation if the interface has one or two methods and does not affect readability

b) a situation where I cannot justify the creation of a new class, for example, in swing, when you need to attach an actionlistner to allow JButton for some trivial operation.

0
Jan 28 '09 at 11:08
source share

I agree that many others have said that they are useful for small interfaces when they are used only once. But I would also add that if code external to an anonymous class needs to be modified to work, then do not use an anonymous class.

If you need to start declaring variables as final to host the anon class, since it refers to them, then use the inner class instead. I also saw some nasty code smells where trailing arrays (size 1) are used to return results from anon classes.

0
Jan 28 '09 at 15:05
source share

Anonymous classes do not β€œhide” the code, but they do a TEND to make it somewhat less reusable. Please note that this also applies to closure.

In a sense, they allow some good refactors because you are allowed to pass code to a method. This can be used 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, think that the code of the anonymous inner class that you pass in cannot be reused in your code. If you do the same in some other code, you will have to rewrite it as something other than an anonymous inner class in order to reuse it, and at this point it would be difficult even to know that there is code in another place for reuse.

Along with the lack of reuse, it is difficult to determine the parameterization, which leads to my biggest complaint ... they usually lead to copying and pasting the code.

I saw a lot of graphical interfaces where someone started with anonymous inner classes as event responders. Many had to do something a little different: for example, 5 lines of code, where the only difference is the line in the middle. Once you are used to using inner classes, a simple solution is to copy and paste the block and replace this line.

The decision to create a new "Named" class that has a string parameter and passes this class to all methods is rarely found at someone at this point. This named class can use parameters or inheritance to define different types of behavior, as well as code.

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

0
May 01 '17 at 16:38
source share



All Articles