Tuesday, October 25, 2011

Are Anonymous Inner Classes Evil in Android Apps?

Not intrinsically evil, but potentially problematic enough that they ought to be avoided (just in Android apps)?


I have now encountered two problems -- one handling dialogs, the other a leaked Intent Receiver -- that were both the result of not carefully using anonymous inner classes in an Android app.

Part of the reason it is tricky is that you don't have total control over the life cycle of your application's classes in Android.

In the dismissDialog defect, which is described here, if the Thread were a separate class that did not have access to my activity's privates, then I would be forced to deal with the dependency in a more explicit way.  The problem would have been more immediately obvious.

I love anonymous inner classes.  They're the closest thing we've got to closures in Java.  But in an Android app, it seems wise to either avoid them altogether, or think very carefully about what you're doing when you use one.



No comments:

Post a Comment