Skip to content Skip to sidebar Skip to footer

Is It Bad Practice To Pass The Instance Of An Activity As A Parameter And Finish() It From A Different Class?

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 fol

Solution 1:

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:

  1. Who is responsible for finishing the activity?.
  2. Who knows when to finish the activity?.
  3. Who knows how to finish the activity? (usually the Activity but be certain).

In your case it could be:

  • The activity itself
  • The session manager
  • The algorithm
  • Something else entirely

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 be finished when the SessionManagercompletes the session. You may then have:

sessionManager.redirect(activityManager);

other scenarios could result in

// Make sure when the session completes this activity is finished.
sessionManager.registerAttachedActivity(Activity activity);

or

// Activity must finish when redirect completes.
activity.finish(sessionManager.redirect());

It really isn't as simple as good practice and bad practice it's more about doing it right.

Solution 2:

Would it be alright to use a separate class and mark these methods as static as follows

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.

Or should I be extending the Activities...

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.

Post a Comment for "Is It Bad Practice To Pass The Instance Of An Activity As A Parameter And Finish() It From A Different Class?"