Home > Software engineering >  Should you create a reference the main class in every class in Java?
Should you create a reference the main class in every class in Java?

Time:04-02

I have a big program and I use my main class in almost every class. I usually access by a getInstance method but I do that every time I need it. For example:

OITCPlugin.getInstance().get....

Now I wonder if that is very efficient and if it was better if I declare a variable for it and access the variable instead:

private OITCPlugin plugin = OITCPlugin.getInstance();
...
plugin.get...

And if I only need it in one method is it more efficient and ram saving if I only declare it in the method itself? Thanks in advance!

CodePudding user response:

Singleton pattern is a common approach if you only want one instance of the object. A lot of people regard it as an anti-pattern, yet it is still very popular. Spring beans are singletons, and redux store is a singleton!

If you are only using it in one method, you might as well free up the heap and store it locally in the method, as described here. Freeing up the heap will technically give better performance, but Java is not exactly a super-efficient language anyway, and it also manages the memory for you. Memory generally isn't a problem though, because it's quite cheap and we have lots of it (maybe I should be more careful about my memory management!)

  • Related