neteinstein
neteinstein

Reputation: 17613

Android: AsyncTask recommendations: private class or public class?

I'm currently developing some Android Apps in a team and we've used 2 different approaches during the last months (one that i personally prefere, and the other that the other developer prefers).

Although so far the results are the same, this got me wondering...should we:

Are any of the approachs recommended by Google?

What does your experience say about this (advantages, disadvantages, problems)?

Upvotes: 43

Views: 11196

Answers (2)

Ted Hopp
Ted Hopp

Reputation: 234847

Inner classes are good for representing objects that are meant to be private or somehow intimately tied to the enclosing class. Occasionally there are technical reasons for using inner classes (e.g., simulating closures). They also cut down on namespace pollution.

One disadvantage of inner classes is that if they access private members (fields or functions) of the enclosing class, the compiler will generate accessor functions to those members. Language purists will argue whether this breaking of encapsulation is a Good Thing or a Bad Thing. The access functions add a bit of overhead to each access (which usually isn't a factor, but there it is). Another disadvantage is that it makes the source file more complex and therefore harder to manage. (I've occasionally been stung by editing a function in the inner class while thinking it was in the outer class, and vice versa.) Finally, inner classes tend not to be reusable, while separate classes can often be parameterized to have multiple uses.

These pros and cons are off the top of my head. I'm sure others will have additional thoughts.

UPDATE:

In this Google IO video the inner AsyncTask option is clearly marked as wrong option.

Upvotes: 36

hackbod
hackbod

Reputation: 91341

It doesn't matter, use what makes the most sense for your code. The important thing is to watch for an async task that is holding a reference on an activity after the activity has been destroyed, either implicitly as an inner class of the activity, or explicitly by being given the activity/context object.

Upvotes: 7

Related Questions