On Tue, May 11, 2010 at 4:06 AM, Federico Paolinelli <fedep...@gmail.com>wrote:

> I found myself using the same code for accessing to gps / cell location
> stuff from a couple of activities of my application.
>

Yup, it happens.


> What I was wondering now is, which is the best way to avoid
> code duplication?
>

Don't duplicate code? =P

No, seriously, as soon as you find yourself copying and pasting - stop.
You're doing something wrong. Take all that copy - pasted code and study it.
Determine what it does, how it does, and what the variables are (if any).
All the duplicated stuff should go in one central location. How that is
structured will largely depend on your app and your coding style.

Should I use a superclass for the activities which implements that kind of
> stuff? Use an helper class?
>

Because of the way Android is structured, I find that helper classes make
more sense then super classes. For example, you can't really have a base
activity class that centralizes all common activity functionality, since
some activities have to extend List-, ExpandableList-, or Map- activity, for
example. You can however have a helper class that each Activity has as a
member which they forward their common functionality to.

How do you deal with this kind of problems?
>

Create a helper class, sometimes static if it makes sense, that does the
work you find yourself copying and pasting. For GPS, for example, I have a
class that takes care of starting and stopping the GPS funtionality, keeps
track of the current location, can return it in various forms (coordinates,
named location, etc), notifies of location updates, and handles other
related tasks.

Each activity that requires it just instantiates it with the proper
parameters (provider, criteria, frequency, etc), calls start and stop as
necessary, and lets the class handle the rest.

-------------------------------------------------------------------------------------------------
TreKing - Chicago transit tracking app for Android-powered devices
http://sites.google.com/site/rezmobileapps/treking

-- 
You received this message because you are subscribed to the Google
Groups "Android Developers" group.
To post to this group, send email to android-developers@googlegroups.com
To unsubscribe from this group, send email to
android-developers+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/android-developers?hl=en

Reply via email to