1

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 ?

Darwind
  • 7,284
  • 3
  • 49
  • 48
MRB
  • 422
  • 1
  • 8
  • 16

3 Answers3

8

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");
// ...
Simon
  • 14,407
  • 8
  • 46
  • 61
Ali Behzadian Nejad
  • 8,804
  • 8
  • 56
  • 106
  • What about the `code` which relies on another class and static modifier is a weaker type than the code? – Norlihazmey Ghazali Jun 04 '16 at 14:53
  • Why should be the methods static and not non-static? – karlihnos Jul 07 '17 at 10:11
  • 1
    @karlihnos If you use static methods, you can call them without instantiating Util class. For example: Util.methodOne("some string"). Otherwise you have to create a object of Util class and then call its methods: Util u = new Util(); u.methodOne("some string"); – Ali Behzadian Nejad Jul 09 '17 at 09:53
  • @AliBehzadianNejad Thxs. This is clear to me. But is it the only reason to decide using statics methods against non-static? only because of the instantiation? – karlihnos Jul 21 '17 at 12:34
5
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...

WarrenFaith
  • 57,492
  • 25
  • 134
  • 150
1

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

Tom
  • 340
  • 1
  • 7