In my Android project, I define a few callbacks to operate on button clicks, connectivity events, or UI events such as Dilaog.onShow(). For demo purposes, I have chosen a Runnable interface that must be launched from some Activity code. With Java, I have different ways to express myself.
One pattern would be to use anonymous class
runOnUiThread(new Runnable() {
public void run() {
doSomething();
}
});
private void doSomething() {
}
another - to define an internal private class, i.e.
private DoSomething implements Runnable {
public void run() {
// do something;
}
}
...
runOnUiThread(new DoSomething());
yet another - to use a private member, like this:
private final Runnable doSomething = new Runnable() {
public void run() {
// do something;
}
}
...
runOnUiThread(doSomething);
Here is another, which I like best, because on one hand it does not actually construct objects unless someone really uses it, because it avoids extra classes, because it can take parameters if needed.
private Runnable doSomething() {
return new Runnable() {
public void run() {
// do something;
}
}
}
...
runOnUiThread(doSomething());
I am not looking for the arguments of taste or religious belief, but of code maintainability and performance. I would like to receive hints and advices that could help me develop my own preference, possibly - different preferences according to the given circumstance.
Progress of Java has rendered this question obsolete, see the accepted answer.
I don't believe there is any idiomatic way to handle callbacks.
I usually inline an anonymous class first. When the method gets too big, I extract the class creation into a separate function. When the class gets too big, I extract to its own file.
If you are using an IDE like Eclipse you can perform all these refactorings automatically and safely.
Like @Manuel Silva and @Toby Champion, I dislike anonymous inner classes. They are somewhat hard to read, aren't very "OO" in that they can't be extended, can't have DIP, setters or whatever to tweak behavior, etc..., and they often end up violating the DRY principle when you add the same code in 27 different places.
I tend to use private members (your option #3), or a private function (your 4th style) typically named getAsRunnable().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With