What is the preferred way to organize callbacks?

In my Android project, I define several callbacks to work with button clicks, connection events, or user interface events such as Dilaog.onShow (). For demonstration purposes, I chose the Runnable interface, which should be launched from some activity code. With Java, I have different ways to express myself.

One of the patterns will be using an anonymous class.

runOnUiThread(new Runnable() { public void run() { doSomething(); } }); private void doSomething() { } 

the other is for defining an inner private class, i.e.

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

another is to use a private member, for example:

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

Here is another one that I like the most, because on the one hand it doesnโ€™t actually create objects unless someone really uses it, because it avoids the extra classes, because it can take parameters if necessary.

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

I'm not looking for arguments of taste or religious beliefs, but in terms of service and code performance. I would like to receive tips and advice that could help me develop my own preferences, perhaps different preferences in accordance with this circumstance.

Spoiler:

Java progress has made this question obsolete; see accepted answer.

+4
source share
5 answers
0
source

I do not believe that there is any idiomatic way to handle callbacks.

I usually insert an anonymous class first. When the method gets too big, I retrieve the class creation into a separate function. When the class gets too big, I extract it to my file.

If you use an IDE, such as Eclipse, you can perform all these refactorings automatically and safely.

+2
source

Like @Manuel Silva and @Toby Champion, I don't like anonymous inner classes. They are difficult to read, they are not very โ€œOOโ€ because they cannot be extended, cannot have DIPs, setters or anything else to change behavior, etc., and they often violate the DRY principle when you add the same code in 27 different places.

I prefer to use private members (your option # 3) or a private function (your 4th style), commonly called getAsRunnable ().

+2
source

I'm very new to Android, but anonymous classes make me sick and it seems like you have an alternative to runOnUiThread: AsyncTask discussed here: runOnUIThread question

+1
source

From my point of view, an anonymous class really reduces readability. Because Ui code is often very verbose, adding anonymous callbacks for each button can lead to very large classes. As a result, I use internal private classes.

0
source

All Articles