-2

I have Util classes where i have many methods to be used in all over project. My question is - considering memory heap, performance what is best to use a static method by class reference or non static method called by object of that class. For example:

public class Utilities {

    private static Utilities utils;

    public static Utilities getInstance() {
        if (utils == null)
            utils = new Utilities();
        return utils;
    }

    public static void someMethod() {

    }

    public void someMethod2() {

    }

}

and

public static void main(String[] args) {
    Utilities.someMethod();
    Utilities.getInstance().someMethod2();
}

Which is correct way for my requirement?

Khemraj Sharma
  • 57,232
  • 27
  • 203
  • 212
  • 1
    There's no major *contract*-related difference. You just need to consider unit testing for caller classes (harder with static methods). Otherwise, it comes down to preference (static imports, etc.) – ernest_k Apr 25 '18 at 17:36
  • 1
    What you showed here looks like "singleton vs static context". In that case this should be related: https://stackoverflow.com/a/12367609, [When is Singleton appropriate?](https://softwareengineering.stackexchange.com/q/252) – Pshemo Apr 25 '18 at 17:38
  • @Ernest Sorry, i didn't get you clearly, is this same? – Khemraj Sharma Apr 25 '18 at 17:38

1 Answers1

1

It won't matter unless you have a very specific goal in mind. Class or method declaration format can be tweaked e.g.:

It would make sense to ensure that methods in the most critical section of your application are inlined but this matter only if your application is CPU-bound. A single call to an external resource e.g. database query will be in orders of magnitude more expensive that local code.

The code should be redable before you start optimizing it. static methods are much harder to unit test so they probably should be avoided if they contain significant logic that requires unit testing.

Karol Dowbecki
  • 43,645
  • 9
  • 78
  • 111
  • So singleton pattern is preferable? – Khemraj Sharma Apr 25 '18 at 17:46
  • Or a dependency injection framework like [Spring](https://en.wikipedia.org/wiki/Spring_Framework). Some people consider singleton an anti-pattern but rolling out DI framework in a simple application might be an overkill. – Karol Dowbecki Apr 25 '18 at 17:47