Take the following example. There's an object I want to use, call it a Doodad. Doodad elements have poorly implemented handling of browser events. Typical instantiation of a Doodad would be Doodad someDoodad = new Doodad();. Obviously this isn't suiting my needs because of the poor event handling. Is it appropriate for me to override the onBrowserEvent() method, like so:
Doodad someDoodad = new Doodad() {
#Override
public void onBrowserEvent(Event event) {
switch (DOM.eventGetType(event)) {
case Event.ONDBLCLICK:
case Event.ONFOCUS:
case Event.ONCLICK:
if (!isEnabled()) {
return;
}
break;
}
super.onBrowserEvent(event);
}
};
Obviously this is a simple example, but when might I not want to use an anonymous inner class? Is it ever explicitly disallowed or impossible?
I'm seeing lots of answers to the first question, but none of the answers so far answer the second: Is it ever explicitly disallowed or impossible to use an anonymous inner class?
Typically the best usage of anonymous inner classes is when you want to create only one instance of specific implementation of this class. And when the implementation is pretty simple. Ideally it should contain 1-2 lines of code.
In your case it is still OK although your method onBrowserEvent() is longer than 2 lines.
Anonymous inner classes is Java's syntax for creating closures. Here's an approximate example:
interface Adder {
int add(int arg);
}
...
Adder createAdder(int n) {
final int nf = n;
return new Adder() {
int add(int arg) { return arg + nf; }
}
}
Method createAdder creates what essentially is a function using a closure to capture the passed value n. Closures are important in functional programming which is trying to make it into mainstream. This is why everyone is screaming that we need "real" closures in Java (i.e. mostly better syntax than in my example).
(Of course I'm not answering the question asked; I think what I'm saying is that anonymous classes are good for what I described above. for almost everything else I would create a named inner class because if anything name is self-documenting and is in my opinion easier to read)
Often, an event listener is a piece of code that is not very generic, but is tied to a specific widget, a button, a text-field, whatever. In such a case, the code does not need to be properly exposed for the world to reuse it. It is easier to define it where it is used, in place, and that's what anonymous inner classes are for. They allow to quickly embed pieces of code inside another method, without having to worry about class names, packages, visibility, or re-usability.
Of course, what you can do with anonymous inner classes can always be done with proper stand-alone classes. But it makes more sense to do it this way when your event handling class is generic enough (can handle lots of events), is reusable, is stateful, or more generally when there is some benefit from extracting the event management code from the code that defines the event-generating element.
I'm not sure I understand specifically your question, I hope this piece of info will help you find your answer. Do not hesitate to ask further questions.
I would suggest anonymous classes when it implements one method and/or is half a screen full.
If the anonymous has non trival piece of code its worth having a named class IMHO.
My take:
Anonymous inner classes: Callback from one function (so you don't write the code twice)
Named inner classes: Callbacks from several functions (or a class that you need only for the internal logic of the parent class)
I only use an anonymous inner class when it contains a very small amount of code. Reason is IMO it clutters up the code and makes it less readable.
If there is more code required, I prefer to create a new class, extending the base class (in this case 'Doodad()'
In your example you would want to create a separate class. This is because of the reason why you are overriding the method. That is, there is poor handling for browser events.
Specifically, you may want to create these improved Doodads in a couple of different places. And what happens if the event handling is updated and improved in the future? You'll want to remove all of these improved Doodads and use the proper implementation. Trying to find all your anonymous Doodads may be tiresome or tricky. Whereas if you have a separate named class then refactoring out this class will be easy.
In addition the reason for your improving the Doodad can be self documenting if you create a separate class for it. Whereas if you just have an anonymous class then you will have to write comments or leave future maintainers guessing why you've done what you've done.
eg.
public class ImprovedBrowserEventHandlingDoodad extends Doodad {
...
}
Anything that resembles a closure is normally a good candidate for using an anonymous class
eg.
new Thread(new Runnable() {
#Override
public void run() {
doSomething();
}
}).start();
You only want to do something in this one specific set of circumstances and there is no need to copy and paste the code somewhere else or to refactor it into a method.
Event handlers for GUIs are typical in using anonymous classes because their use is limited to the how the GUI is designed and there is no need to create a separate instance of the event handler outside the specific component that is using it. For instance, when you mouse over a scroll bar its appearance generally changes. Nothing else in the program will cause this change and typically the event handler will be a couple of lines telling the scrollbar to change its appearance eg. scrollbar.setMouseOverEffect(true);.
Related
EDIT
Even though I use a pseudo-Java syntax below for illustration, this question is NOT limited to any 1 programming language. Please feel free to post an idiom or language-provided mechanism from your favorite programming language.
When attempting to reuse an existing class, Old, via composition instead of inheritance, it is very tedious to first manually create a new interface out of the existing class, and then write forwarding functions in New. The exercise becomes especially wasteful if Old has tons of public methods in it and whereas you need to override only a handful of them.
Ignoring IDE's like Eclipse that though can help with this process but still cannot reduce the resulting verbosity of code that one has to read and maintain, it would greatly help to have a couple language mechanisms to...
automatically extract the public methods of Old, say, via an interfaceOf operator; and
by default forward all automatically generated interface methods of Old , say, via a forwardsTo operator, to a composed instance of Old, with you only providing definitions for the handful of methods you wish to override in New.
An example:
// A hypothetical, Java-like language
class Old {
public void a() { }
public void b() { }
public void c() { }
private void d() { }
protected void e() { }
// ...
}
class New implements interfaceOf Old {
public New() {
// This would auto-forward all Old methods to _composed
// except the ones overridden in New.
Old forwardsTo _composed;
}
// The only method of Old that is being overridden in New.
public void b() {
_composed.b();
}
private Old _composed;
}
My question is:
Is this possible at the code level (say, via some reusable design pattern, or idiom), so that the result is minimal verbosity in New and classes like New?
Are there any other languages where such mechanisms are provided?
EDIT
Now, I don't know these languages in detail but I'm hoping that 'Lispy' languages like Scheme, Lisp, Clojure won't disappoint here... for Lisp after all is a 'programmable programming language' (according to Paul Graham and perhaps others).
EDIT 2
I may not be the author of Old or may not want to change its source code, effectively wanting to use it as a blackbox.
This could be done in languages that allow you to specify a catch-all magic method (eg. __call() in php). You could catch any function call here that you have not specifically overriden, check if it exists in class Old and if it does, just forward the call.
Something like this:
public function __call($name, $args)
{
if (method_exists($old, $name))
{
call_user_func([$obj, $name], $args);
}
}
First, to answer the design question in the context of "OOP" (class-oriented) languages:
If you really need to replace Old with its complete interface IOld everywhere you use it, just to make New, which implements IOld, behave like you want, then you actually should use inheritance.
If you only need a small part of IOld for New, then you should only put that part into the interface ICommon and let both Old and New implement it. In this case, you would only replace Old by ICommon where both Old and New make sense.
Second, what can Common Lisp do for you in such a case?
Common Lisp is very different from Java and other class-oriented languages.
Just a few pointers: In Common Lisp, objects are primarily used to structure and categorize data, not code. You won't find "one class per file", "one file per class", or "package names completely correspond to directory structure" here. Methods do not "belong" to classes but to generic functions whose sole responsibility it is to dispatch according to the classes of their arguments (which has the nice side effect of enabling a seamless multiple dispatch). There is multiple inheritance. There are no interfaces as such. There is a much stronger tendency to use packages for modularity instead of just organizing classes. Which symbols are exported ("public" in Java parlance) is defined per package, not per class (which would not make sense with the above obviously).
I think that your problem would either completely disappear in a Common Lisp environment because your code is not forced into a class structure, or be quite naturally solved or expressed in terms of multiple dispatch and/or (maybe multiple) inheritance.
One would need at least a complete example and large parts of the surrounding system to even attempt a translation into Common Lisp idioms. You just write code so differently that it would not make any sense to try a one-to-one translation of a few forms.
I think Go has such a mechanism, a struct can embed methods from another struct.
Take a look here. This could be what you are asking as second question.
How is it helpful to use anonymous class if every time we have to define a class while invoking a constructor of an interface.Wouldn't it be more better to simple use a generic type instead?
Anonymous classes is frequently used in GUI applications. When you only need to declare and create object of a class at the same time, it can make the code more precise.
Here is an example:
btn.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
System.out.println("Hello World!");
}
});
Anonymous classes are not defined every time they are instantiated. They get compiled into bytecode just like other classes, with a name e.g. MyEnclosingClass$1. See this post for more information: How are anonymous classes compiled in Java?
Tangentially, reflection can be used to identify them at runtime using Class.isAnonymousClass().
It depends on the situation; in some cases it will be better to use an anonymous class, and in others, it will be better to use a concrete class that implements the required interface.
If you believe that you'll need to provide the same anonymous class definition repeatedly, it will likely save you time to pass an instance of a concrete class that implements the required interface.
The Java language provides anonymous class syntax as a convenience.
To give you just a taste, here's a quick example from my own experience: Having lists backed by functions.
In general, anonymous classes have (among others) the following uses:
Suppose you want to have an object (an instance, not a class) whose behavior depends on some value available at runtime. Without anonymous classes, you can do this by setting fields (or calling state-changing methods) - but you can't have different code executing. Now, true, you could have bunch of switch() statements in your class' method code - but that completely decouples the definition of the behavior from its context. Another way you could go is to use a named subclass, but that's a lot of code, and it creates a noun you don't really want to exist.
Functional Programming! Until Java 8 comes along, anonymous functions are just about the only way you can pass around functions, which are not first-class citizens in Java. With those, you can perform many neat and elegant tricks like my example above.
Let's say I have a labyrinth with AI characters, where the users define the characters. Each user provide the classes for their individual characters. All the characters/classes extend some class/type C which has method control().
I want to do call each user's control() method, but I don't know how many users there will be or what classes they will provide. How do I resolve this problem?
EDIT: I wanted to convey that I do not know how many subclasses there are, or what their names are. Therefore, I am not able to place those subclasses in the code statically.
EDIT 2: Is there a way of doing this WITHOUT using reflection? I am aware that reflection solves the problem, but I hoped there was a cleaner implementation.
EDIT 3: It completely necessary to have the users create the different classes, as the point of the program is to test competing AIs.
btw, I am writing this in Java.
First of all, you need to decide if the different characters' behavior is really going to be as differentiated as to need Java code to implement the particular behaviors. Perhaps the behavior can be expressed with a single class and only modified by setting different values for parameters such as speed, health, attack strength etc. In this case you would get rid of the inheritance problem altogether and use a single class while users would only provide different configurations.
Now, if you really need very custom behavior and load custom Java classes, I see two main solutions.
First is the standard one. It uses just a tiny bit of reflection. You define an interface, for example:
public interface C {
void control(); //Params skipped for brevity
}
Now, your users create classes which implement this interface. The only problem is how to create an instance of the player's class. Once you have it, you call its control() or other methods via the interface. First, users need to make this class loadable. Thiscan be done through the network or in other complex ways but the simplest is that they put their .class or .jar file in their classpath when they run your application. Now all you need is to create an instance of the class. Assuming you specify the requirement that the class have a zero-argument constructor (you can define a method in your interface to load some configuration and perform initialization later on), you would be doing something like:
C gameCharacter = (C)Class.forName("your.fully.qualified.ClassName").newInstance();
Apart from error handling, that's all the reflection you need. You can now call all methods of interface C on your gameCharacter object - without knowing who or how wrote it and what exactly the methods do.
The other solution would be to use Groovy or another similar language to compile and run code on the fly. In this case you don't need the custom JAR in the classpath and you can even get around the need to know the name of the class to be loaded. Your user can provide the Java code of control() method in the form of text, and you can have a stub class whose control() method only compiles and executes the Groovy code the user provided. This may be more convenient, but requires the custom character code to be provided to you as source code, not compiled JAR, which may be a problem for some users. Also, this solution is more convenient if the implementations are going to be short and self-contained while the separate JAR and loading via reflection is better if the loaded code is more complex, uses helper classes apart from the main class etc.
The whole thing about inheritance is that you don't need to know the exact type.
If you have a reference to an object that is of type C or a subclass of C, you can call your "control()" method on them and it will call the right method, i.e. the one implemented by the child class.
Not knowing how many users means you'll have to use a list or something and loop over it.
public class AIGame {
public static void main(String[] args) {
List<AICharacter> characters = new ArrayList<AICharacter>();
characters.add( new ReallySmartAICharacter() );
characters.add( new ReallyDumbAICharacter() );
for ( AICharacter c : characters ) {
c.control();
}
}
}
interface AICharacter {
public void control();
}
class ReallySmartAICharacter implements AICharacter {
#Override
public void control() {
// TODO do something clever here
}
}
class ReallyDumbAICharacter implements AICharacter {
#Override
public void control() {
// TODO do something stupid here
}
}
If all the characters extend some common class, for convenience let's call it Character, then you can use polymorphism to dynamically call each of the control() methods.
In other words, if each subclass of Character overrides control(), then all you need to do is call it normally and Java will figure out which control() method to call.
e.g.
Character[] characters = new Character[2];
characters[0] = new Man(); // Man is a subclass of Character
characters[1] = new Woman(); // same with Woman
character[0].control(); // <- this will call the control() method as defined in Man
The mechanism for this is called late (or dynamic) binding, which you can read more about here: http://en.wikipedia.org/wiki/Late_binding
If the subclasses are not known at compile-time (i.e. they are specified at run-time), then you will need to use reflection to load them.
To keep track of each user, use a dynamically sized List type like a LinkedList or ArrayList. This way you don't need to know how many users there are beforehand.
I have a common jar that uses some unmarshaling of a String object. The method should act differently depending on which application it is called from, how can I do that besides from the fact that I can identify the application by trying to load some unique class it has (don't like that). Is there some design pattern that solves this issue?
As I alluded to in my comment, the best thing to do is to break that uber-method up into different methods that encapsulate the specific behaviors, and likely also another method (used by all of the app-specific ones) that deals with the common behaviors.
The most important thing to remember is that behavior matters. If something is behaving differently in different scenarios, a calling application effectively cannot use that method because it doesn't have any control over what happens.
If you still really want to have a single method that all of your applications call that behaves differently in each one, you can do it, using a certain design pattern, in a way that makes sense and is maintainable. The pattern is called "Template Method".
The general idea of it is that the calling application passes in a chunk of logic that the called method wraps around and calls when it needs to. This is very similar to functional programming or programming using closures, where you are passing around chunks of logic as if it were data. While Java proper doesn't support closures, other JVM-based languages like Groovy, Scala, Clojure, JRuby, etc. do support closures.
This same general idea is very powerful in certain circumstances, and may apply in your case, but such a question requires very intimate knowledge of the application domain and architecture and there really isn't enough information in your posted question do dig too much deeper.
Actually, I think a good OO oriented solution is, in the common jar, to have one base class, and several derived classes. The base class would contain the common logic for the method being called, and each derived class would contain specific behavior.
So, in your jar, you might have the following:
public abstact class JarClass {
public method jarMethod() {
//common code here
}
}
public class JarClassVersion1 extends JarClass {
public method jarMethod() {
// initiailzation code specific to JarClassVerion1
super.jarMethod();
// wrapup code specific to JarClassVerion1
}
}
public class JarClassVersion2 extends JarClass {
public method jarMethod() {
// initiailzation code specific to JarClassVerion2
super.jarMethod();
// wrapup code specific to JarClassVerion2
}
}
As to how the caller works, if you are willing to design your code so that the knowledge of which derived class to use resides with the caller, then you obviously just have the caller create the appropriate derived class and call jarMethod.
However, I take it from your question, you want the knowledge of which class to use to reside in the jar. In that case, there are several solutions. But a fairly easy one is to define a factory method inside the jar which creates the appropriate derived class. So, inside the abstract JarClass, you might define the following method:
public static JarClass createJarClass(Class callerClass) {
if (callerClass.equals(CallerClassType1.class)) {
return new JarClassVersion1();
} else if (callerClass.equals(CallerClassType2.class)) {
return new JarClassVersion1();
// etc. for all derived classess
}
And then the caller would simply do the following:
JarClass.createJarClass(this.getClass()).jarMethod();
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
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?
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.
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(...));
}});
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.
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.
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.
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.
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.
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.
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.
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().
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.
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.
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.
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.
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.