Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the preferred way to organize callbacks? [closed]

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.

like image 368
Alex Cohn Avatar asked Sep 15 '10 14:09

Alex Cohn


Video Answer


2 Answers

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 image 96
Garrett Hall Avatar answered Sep 25 '22 16:09

Garrett Hall


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().

like image 36
user949300 Avatar answered Sep 24 '22 16:09

user949300