Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Helper class best approach android

Tags:

java

android

I was looking at Google I/O Android App iosched link and saw that they use mostly static methods in their helper/util classes. However, I have found many people not recommending the use of static methods in helper classes.

Let's say if I have 3 activities that are doing some work like showing alert dialog or notification, then I need to add the same code in all the 3 activities. What if I am writing in files from 10 different activities. Isn't using a helper class with a static method a better approach than writing same code again and again? if not then what is the best approach.

public class NotificationHelper {

  /**
   * create notification
   * @param context activity context
   * @param title notification title
   * @param contentText notification text
   * @param mNotificationId notification id
   */
  public static void setUpNotification(Context context, String title, String contentText, int mNotificationId) {

    NotificationCompat.Builder mBuilder =
            new NotificationCompat.Builder(context).setLargeIcon((BitmapFactory.decodeResource(context.getResources(),R.drawable.launcher)))
                    .setSmallIcon(R.drawable.ic_notif)
                    .setContentTitle(title)
                    .setContentText(contentText).setPriority(NotificationCompat.PRIORITY_MAX);

    Intent resultIntent = new Intent(context, MainActivity.class);
    PendingIntent resultPendingIntent =
            PendingIntent.getActivity(
                    context,
                    0,
                    resultIntent,
                    PendingIntent.FLAG_UPDATE_CURRENT);
    mBuilder.setContentIntent(resultPendingIntent);
    mBuilder.setOngoing(true);
    NotificationManager mNotificationManager =
            (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    mNotificationManager.notify(mNotificationId, mBuilder.build());
}

  /**
   * cancel notification
   * @param ctx context
   * @param notifyId id of notification to be cancelled
   */
  public static void cancelNotification(Context ctx, int notifyId) {
    NotificationManager nMgr = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);
    nMgr.cancel(notifyId);
  }
}
like image 412
Mohak Puri Avatar asked Jan 25 '26 16:01

Mohak Puri


2 Answers

Usuage of Helper classes is little debatable in object oriented programming. You can use normal class and include the object of the class. Or you may put common code in a base class and then extend it. But if we decide to use Helper classes then below are the few points which may help you as guideline.

  1. Helper classes are the utility entities. They are better used just like utility so prevent the instantiation and extension by marking the default constructor as private.

  2. Expose the ' static ' methods. See if the methods are just needed by the classes in the package as of the utility class, then keep the acess modifer as package-private, and if needed by classes outside also then you can make them public. The intent is to prevent exposing package details too much by public APIs. You can also try to have abstractions in parametrs and return type.

  3. Try to keep such classes as stateless by not having fields. Keeping the ( static ) fields may lead referencing objects even when not needed.

  4. Name such classes properly to let users of the helper class know its intention and also that they are just utility classes. Also name the methods according to use and to minimize the confusions.

like image 166
nits.kk Avatar answered Jan 27 '26 06:01

nits.kk


Few points to remember related to use of Utility classes (some of them already touched upon the previous answer) -

  1. Generally if you have a couple of activities doing something common like using the same networking layer, showing general error prompts and notifications then the best approach is to put them in a BaseActivity and let all your activities extend them. If you may, use OOPS concepts like grouping behaviors into interfaces, defining abstract methods which child activities must extend and stuffs like that. Avoid doing anything specific in the BaseActivity and let the child activities take as much control as possible.

  2. If you have to have utility classes, make them singleton and without any state.

  3. Avoid doing async tasks in the utility methods. Remember each component on Android has a lifecycle and any async task you do must be tied to the lifecycle of the hosting component. So for e.g if you are doing a File operation which you think must take a while, then wrap it in a asynctask or something in your calling component.

  4. Utility classes are good members for injection (my opinion !!). Try using a DI library like Dagger to make your life easier if you end up using too many utility libraries.

like image 22
Dibzmania Avatar answered Jan 27 '26 06:01

Dibzmania



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!