views:

56

answers:

1

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, line this:

private final Runnable doSomething = new Runnable() {
    public void run() { 
        // do something; 
    }
}
...
runOnUiThread(doSomething);

I guess that the choice is mostly an issue of taste or religious belief, but I would like to receive hints and advises that could help me develop my own preference, possibly - different preferences according to the given circumstance.

Update: I thought of the fourth style, with its own virtues:

private Runnable DoSomething() { 
    return new Runnable() {
        public void run() { 
            // do something; 
        }
    }
}
...
runOnUiThread(DoSomething());

I like it 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.

A: 

From my point of view, anonymous class really decrease readability. Because Ui code is often very verbose, adding anonymous callbacks for every button can lead to very very big classes. As a consequence I am using internal private classes.

Manuel Selva
Thanks, I have fixed the first example to express the idea better: the anonymous callback in my case just calls a private method, less likely two.
Alex Cohn