I have a few Activities that use the exact same methods logout()
and redirect()
multiple times.
Would it be alright to use a separate class and mark these methods as static
as follows:
public class AuthUtil {
public static void redirect(SessionManager manager, Activity activity) {
manager.redirect();
activity.finish();
}
public static void logout(SessionManager manager, Activity activity) {
manager.logoutUser();
activity.finish();
}
}
And call them from the activity by:
AuthUtil.logout(mSession,this);
Or should I be extending the Activities that use the method to a common Activity
class and just put the methods there (except without the parameters since the methods wouldn't need them in that case)? However, I won't be able to do this if one of the activities extends FragmentActivity
, another ActionBarActivity
, which is actually the case for me...
Basically, I want to know if it's bad practice to call the activity's methods like that from a separate class body than its own? If so, what should I be doing?
No. It would make very difficult to figure out where are the activities being finished by looking only at the source code of a given activity. And its also hard to see in what thread are those methods running for instance. And finally, because they are static, you'll have to add a new method if an activity needed to perform additional or different actions when redirecting or logging out.
In my experience it is not a good idea to tie activities to an inheritance hierarchy, and you named a few good reasons for not doing so. If you need code reuse try to use composition instead.
I'd always call
Activity.finish
from the very same activity, in fact I'd like to have the whole lifecycle picture contained in the activity's code. But this is just what my guts tell me, there's no definitive correct answer to your question.No it is not considered bad practice - but choosing that route because it is easiest may well be a decision you later regret.
You should ask yourself the following questions:
Activity
but be certain).In your case it could be:
Once you have answered those questions you should have a good idea how to implement.
Remember that you could also create a third object, perhaps an
ActivityManager
that takes responsibility. It could hold a list of activities that need to befinish
ed when theSessionManager
completes the session. You may then have:other scenarios could result in
or
It really isn't as simple as good practice and bad practice it's more about doing it right.