How to organize helper functions

可紊 提交于 2019-12-06 15:45:26

问题


I need to create lot of helper routines for converting strings.

Something like :

String Function1(String s) {}

I would like to call them from any Activity.

What is the best way to do this ? Do I need to create a class or not ? I was thinking just to have one separate file with all these functions. Is this a candidate for a package or not ?


回答1:


Create a class with public static methods, then you can call them every where with ClassName.methodName(parameters):

public class Util {
  public static String methodOne(String param) {
      //do something
      return param;
  }

  public static String methodTwo(String param) {
      //do something
      return param;
  }

  //...
}

Inside other classes:

String someString = Util.methodOne("Some String");
// ...



回答2:


Package: util
Class: StringUtils
Methods: all static

That is what I would do (and actually always do).

You can and should differ between the types. Normally you group stuff like DateUtils, StringUtils, AndroidUtils, MathUtils etc...




回答3:


I would go with a utility class and I always put my utility classes in a com.xxx.xxx.util package.



来源:https://stackoverflow.com/questions/15912224/how-to-organize-helper-functions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!