Search code examples
javalambdacoding-styleanonymous-classprivate-class

What is the preferred way to organize callbacks?


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.

Spoiler:

Progress of Java has rendered this question obsolete, see the accepted answer.


Solution

  • Today, when Java 8 is almost available for Android, and Android Studio automagically pretends that lambdas are already supported, the anonymous class (#1) solution seems to be the obvious choice:

    collapsed

    expanded