I would like to ask what is the good practice on using anonymous classes vs. named inner classes?
I am writing an Android application, which includes many UI elements (buttons, text fields, etc). For many of them I need some kind of listeners, so in onCreate
of the application I have bunch of quite small anonymous classes like:
someButton.setOnClickListener(
new View.OnClickListener() {
public void onClick(View v) {
// do something...
}
}
);
Each of of such anonymous class is 5 - 20 lines big - small enough and fits good for recommendations from Java™ in a Nutshell book:
In general, you should consider using an anonymous class instead of a local class if:
- The class has a very short body.
- Only one instance of the class is needed.
- The class is used right after it is defined.
- The name of the class does not make your code any easier to understand.
But the problem, IMO, is that onCreate
becomes quite big and the code becomes more complex to read and understand by quick looking in to it. It is still easy to understand, but simply too big.
So what would be better practice in such case - have bunch of small inner sub-classes, where each of it is nicely separated , but used just once or better keep using anonymous classes instead?