This article is participating in the Java Theme Month – Java Debug Notes Event, see the event link for details

Why are static variables considered evil?

I’m a Java programmer who is new to the corporate world. Recently, I’ve developed an application using Groovy and Java. All the code I write uses a lot of static variables. The senior technician asked me to reduce the amount of static electricity I used. I’ve already googled the same thing and found that many programmers are pretty opposed to using static variables.

I find static variables easier to use. And I think they’re valid, too (correct me if I’m wrong), because if I had to make 10,000 calls to a function in a Class, I’d be happy to make that method static and use the direct class.methodCall () method on it, rather than messing up memory with 10,000 instances of classes, right?

Furthermore, static functions reduce interdependencies on other parts of the code. They can serve as perfect state owners. In addition, I have found that static methods are widely implemented in certain languages such as Smalltalk and Scala. So why is this oppression of static so prevalent among programmers, especially in the Java world?

PS: Correct me if I’m wrong about static.

Answer:


A lot of knowledge points, really need to write out will master ! ! !   \color{purple} a lot of knowledge points, really need to write out just can master!! {~}

Static variables represent global state. This is hard to reason about, and hard to test: If you create a new instance of an object, you can infer its new state in the test. If I’m using code that uses static variables, it can be in any state – anything can change it.

I could go on for a while, but the bigger idea to consider is that the tighter the scope of things, the easier it is to reason. We’re good at thinking about small things, but without modularity, it’s hard to reason about the state of a million-line system. By the way, this applies to all sorts of things – not just static variables.

Answer:

It’s not very object-oriented: one of the reasons some people might view statics as “evil” is that they are antithetical to the object-oriented paradigm. In particular, it violates the principle of encapsulating data in objects (which can be extended, hidden information, and so on). Static, the way you describe using them, is essentially using them as global variables to avoid dealing with issues like scopes. However, global variables are one of the defining features of procedural or imperative programming paradigms, not of “good” object-oriented code. This is not to say that program paradigms are bad, but I get the impression that your supervisor wants you to write “good object-oriented code,” and that you really want to write “good program code.”

There are many problems in Java that aren’t always immediately obvious when you start using static methods. For example, if two copies of your program are running in the same VM, will they split the values of static variables and confuse each other? Or what happens when you extend a class, can you override static members? Does your VM run out of memory because it has a lot of static data in memory and can’t reclaim that memory for other instance objects that need it?

Object lifetime: In addition, the lifetime of a static variable matches the entire runtime of the program. This means that even after you have finished working with the class, the memory of all these static variables cannot be garbage collected. For example, if you make variables non-static and create a single instance of the class in the main () function, then ask your class to execute that particular function 10,000 times after making those 10,000 calls. Then the reference to the single instance is removed, and all static variables can be garbage collected and reused.

Prevent some reuse: In addition, static methods cannot be used to implement interfaces, so static methods can prevent some object-oriented functionality from being available.

Other options: If efficiency is your primary concern, there are probably better ways to solve the speed problem than just considering the advantage that calls are generally faster than creation. Consider whether transient or volatile regulators need to be used anywhere. To preserve the ability to inline, mark the method as final instead of static. Method parameters and other variables can be marked as final to allow some compiler optimizations based on assumptions that these variables can be changed. An instance object can be reused multiple times, rather than creating a new instance each time. In general, a compatible optimization switch should be turned on for your application. Perhaps the design should be set up so that 10,000 runs can be multithreaded and take advantage of a multiprocessor kernel. If portability is’ please be aware that native methods may get faster than static methods.

If for some reason you don’t want to have multiple copies of an object, use the singleton design pattern compared with static objects, has advantages, such as thread-safe (assuming your singleton code correctly), allow the lazy initialization, ensure object when use is properly initialized, subclassing, advantage in testing and refactor the code, let alone, If you change your mind at some point and just want an instance of an object, it’s much easier to remove the code to prevent duplicate instances than to refactor all the static variable code to use instance variables. I used to have to do this, it wasn’t fun, and you ended up having to edit more classes, which increased the risk of introducing new errors… So good is the case with setting them “right” the first time, even if it seems to have its drawbacks. For me, if you decide you need multiple copies of something yourself, the rework that might be required is probably one of the most compelling reasons to use static variables as infrequently as possible. So I also disagree with you that statics reduce interdependence, and if you have a lot of statics that you can access directly, as opposed to objects that “know how to do it,” THEN I think you’ll end up with more coupling code. Things “.

The article translated from kgs4h5t57thfb6iyuz6dqtun5y ac4c6men2g7xr2a – stackoverflow – com. Translate. Goog/questions / 7…

In this article, I refer to the static inner class worker and the inner class rejection policy in ThreadPoolExecutor, as well as the singleton pattern implemented by the static inner class and the singleton pattern implemented by the URL template class in Java source

Static classes in Java?


Welcome to my column S t a c k O v e r F l o w . I select the best questions and answers and test them frequently in interviews ! ! !   \color{red} Welcome to my column StackOverFlow, I will filter the quality of the interview test!! {~}


There are the latest and elegant ways to do this, and I will write my thoughts on this q&A at the end of the article \color{red} has the latest, elegant implementation, and I will also write my opinion on this question at the end of the article {~}

Thank you for reading this, if this article is well written and if you feel there is something to it

Ask for a thumbs up 👍 ask for attention ❤️ ask for share 👥 for 8 abs I really very useful!!

If there are any mistakes in this blog, please comment, thank you very much! ❤ ️ ❤ ️ ❤ ️ ❤ ️