0

I'm trying to decide between two different ways of writing optimal code for utility classes.

OPTION 1:

public class UtilityClass {

    public static ClassB method1(ClassA obj1, ClassA obj2) {
          //Some lines of code
    }

    public static ClassC method2(ClassD obj1, ClassD obj2) {
          //Some lines of code
    }
}

OPTION 2:

public enum UtilityEnum {
    INSTANCE;

    public ClassB method1(ClassA obj1, ClassA obj2) {
          //Some lines of code
    }

    public ClassC method2(ClassD obj1, ClassD obj2) {
          //Some lines of code
    }
}

OPTION 1 I believe gives room for inlining. OPTION 2 will place the instance in heap. Does this affect performance? Which is the most preferable way?

  • Even if there could be performance implications, that would be minor. But one thing you may need to consider is unit testing. Unit testing static methods isn't always trivial, but the difference may be negligible depending on your actual implementation. – ernest_k Jun 04 '18 at 19:05
  • Having an instance adds nothing here. It's just a static method with an extra annoying name in it, effectively. – Andy Turner Jun 04 '18 at 19:07
  • 1
    https://softwareengineering.stackexchange.com/ might be a better place for this question. – Jon Adams Jun 05 '18 at 00:04

1 Answers1

1

If you can use option 1, this is the best option because the simplest but there are cases where it will not be possible. In fact if your utility method depends on one or more other classes (dependencies), with option 1 you'll need to add the required dependency (s) as parameter (s) of your utility method. With option 2, you can initialize your singleton with its dependencies without having to change the signature of each utility method.

Ask yourself : Do I really need a singleton in this case ? (see On design patterns: When should I use the singleton?) If no, solution 1 is more than enough.

Sébastien Helbert
  • 2,185
  • 13
  • 22