Can you make objects static even if they are not needed?

I have many programs that declare objects at the top of my class. This object will only be modified from its own class, and there will never be more than one instance of this class running at the same time. Does it make sense to declare objects as static ?

 public class MyClass { private Map<String, Object> myMap; // any reason to make this static? // constructor and other code here } 
+4
source share
3 answers

Is there any use for declaring objects as static?

Not really, no.

Of course, there is no performance benefit. This is because statics are actually stored in (hidden) static frame objects that live on the heap. Ultimately, JIT will generate native code to retrieve a static variable that is no faster than fetching an object variable.


It can be argued that it is more convenient to use statics to share some data structure β€œglobally” within an application. But this convenience has some significant drawbacks. The biggest of them is that statics makes testing harder and they make code reuse more difficult.


However, you should not confuse the general case with the specific case where the static value has or refers to an immutable value or data structure; for example, as a String constant or a constant mapping. They can be justified both from the point of view of design and from a practical point of view; eg.

  public static final String THE_ANSWER = "Forty two"; private static final Map<String, Integer> SCORES; static { Map<String, Integer> map = new HashMap<>(); tmp.put("perfect", 100); tmp.put("average", 50); tmp.put("fail", 20); SCORE = Collections.unmodifiableMap(map); } 

This is good ... so far there is no way for different (current or future) precedents to require different meanings / comparisons / whatever. If possible, then static can be harmful.

0
source

Declaring variables as static makes the variable shared between all objects of the class (in your MyClass example) another, that you can make static methods that return a variable without creating an object of the class

 MyClass.method(); 

sometimes it makes more sense than creating a MyClass object, then it calls a method, for example, the Math class has one question: if you want to have only one instance of MyClass, check out the Singleton Design template, which provides only an instance of the class

+1
source

The only reason that members are static is constant. public static final Sting SOME_CONSTANT = "amazing"; it’s easier to access a static than an instance.

The reasons for not using static elements are testing (how easy is it to falsify a static member?) Or (in particular, using a card) thread safety.

+1
source

Source: https://habr.com/ru/post/1493773/


All Articles