Why static variables are bad
Active 3 years, 1 month ago. Viewed 6k times. Improve this question. Maicake Maicake 2 2 silver badges 6 6 bronze badges. Possible duplicate of Is it bad practice to use public fields? It is trivally easy for you to find answers to this question by simply search on the search engine of your choice for "why are global variables bad? DavidArno for the context of this question, these are essentially the same - the only difference of using static accessor methods is insubstantial here — gnat.
Add a comment. Active Oldest Votes. One alternative is to make the dependency explicit: 1. By managing the initialization ourselves we gain a lot of flexibility: we can supply a different Counter class during testing.
Improve this answer. This answer mentions something between the lines which I found to be one of the most important pieces of know-how gained through experience: If you can't decide between class A and class B, the correct answer is probably class C. Class C being the Counter class in your example. I second that. There are two cases where this appears often: one is a circular dependency, and the other is when you can't decide where to put behavior.
In both cases, there are again two possible solutions: one, there is a third component missing, or two the opposite , they are actually one component.
Maicake probably not, or at least not as strongly. I'm not super familiar with Android development. If Android enforces some singleton instance, then it might be more convenient to use that singleton to store global data and not make the dependencies more explicit. However, in a nontrivial app you will likely want to keep Android-specific parts out of your business logic.
And you might still want to encapsulate the global data through methods. Kilian Foth Kilian Foth k 43 43 gold badges silver badges bronze badges. This doesn't answer the question in any way. Second, about static methods. Static methods are not so bad, but they can quickly reduce performance. For example, think about a method that compares two objects of a class and returns a value indicating which of the objects is bigger tipical comparison method this method can be static or not, but when invoking it the non static form will be more eficient since it will have to solve only two references one for each object face to the three references that will have to solve the static version of the same method one for the class plus two, one for each object.
But as I say, this is not so bad, if we take a look at the Math class, we can find a lot of math functions defined as static methods. This is really more eficient than putting all these methods in the class defining the numbers, because most of them are rarelly used and including all of them in the number class will cause the class to be very complex and consume a lot of resources unnecesarilly.
In concluson: Avoid the use of static variables and find the correct performance equilibrium when dealing with static or non static methods. There's nothing wrong with static variables per se. It's just the Java syntax that's broken. Each Java class actually defines two structures- a singleton object which encapsulates static variables, and an instance.
Defining both in the same source block is pure evil, and results in a code that's hard to read. Scala did that right.
Static variables are not good nor evil. They represent attributes that describe the whole class and not a particular instance. If you need to have a counter for all the instances of a certain class, a static variable would be the right place to hold the value.
If you have a small- to midsize-program, where the static variable Global. Now how do I know who set it to its actual value? How do I know, what happens, if I modify it right now? I have grep over the whole source, to collect all accesses, to know, what is going on. If you know how you use it, because you just wrote the code, the problem is invisible, but if you try to understand foreign code, you will understand. Static variables often prevent multiple programs of the same kind running in the same JVM with different values.
You often don't foresee usages, where more than one instance of your program is useful, but if it evolves, or if it is useful for others, they might experience situations, where they would like to start more than one instance of your program.
Only more or less useless code which will not be used by many people over a longer time in an intensive way might go well with static variables.
All the answers above show why statics are bad. The reason they are evil is because it gives the false impression that you are writing object oriented code, when in fact you are not. That is just plain evil. Modularization: consider concepts like IOC, dependencyInjection, proxy etc.. I've played with statics a lot and may I give you a slightly different answer--or maybe a slightly different way to look at it?
When I've used statics in a class Members and methods both I eventually started to notice that my class is actually two classes sharing responsibility--there is the "Static" part which acts a lot like a singleton and there is the non-static part a normal class.
As far as I know you can always separate those two classes completely by just selecting all the statics for one class and non-statics for the other. This used to happen a lot when I had a static collection inside a class holding instances of the class and some static methods to manage the collection. Once you think about it, it's obvious that your class is not doing "Just one thing", it's being a collection and the doing something completely different. Now, let's refactor the problem a little: If you split your class up into one class where everything is static and another which is just a "Normal Class" and forget about the "Normal Class" then your question becomes purely Static class vs Singleton which is addressed in length here and probably a dozen other questions.
Static fields are de facto GC roots see the How Garbage Collection Works section earlier in this chapter , which means they are never garbage-collected! For convenience alone, static fields and collections are often used to hold caches or share state across threads. Mutable static fields need to be cleaned up explicitly. If the developer does not consider every possibility a near certainty , the cleanup will not take place, resulting in a memory leak. This sort of careless programming means that static fields and collections have become the most common cause of memory leaks!
In short, never use mutable static fields—use only constants. If you think you need mutable static fields, think about it again, and then again! There's always a more appropriate technique. I think excessive uses of global variables with static keyword will also leads to memory leakage at some point of instance in the applica. From my point of view static variable should be only read only data or variables created by convention. For example we have a ui of some project, and we have a list of countries, languages, user roles, etc.
And we have class to organize this data. So we agree that this data is "always" present in app. It is practically read only data so we don't need to take care of it's state - thinking about this case we really don't want to have a lot of instances of those data - this case looks a perfect candidate to be static.
Stack Overflow for Teams — Collaborate and share knowledge with a private group. Create a free Team What is Teams? Collectives on Stack Overflow. Learn more. Why are static variables considered evil? Ask Question. Asked 10 years, 3 months ago. Active 23 days ago. Viewed k times. PS: please do correct me if my assumptions about statics are wrong. Improve this question. Vamsi Emani Vamsi Emani 9, 7 7 gold badges 40 40 silver badges 70 70 bronze badges. Just for the sake of saying, there are no static variables or methods on Smalltalk or Scala, exactly because static methods and variables are against the OOP principles.
At least one statement you make is rather curious: "statics reduce the inter-dependencies on the other parts of the code".
In general they tighten the dependencies. The code where the call is made is bound very tightly to the called code. No abstraction between, direct dependency. Your second paragraph is about an entirely different subject, namely static methods. Functional programming also frowns down upon global state as well. If you ever and you should get into FP one day, be prepared to ditch the notion of global state.
If your method can be static then that shows it doesn't depend upon state. If it doesn't depend upon state why would you need to create objects? Why not invoke it times on same object?
Unless you meant invoking it from different locations in which case you obviously need to refactor your code. Show 14 more comments. Active Oldest Votes. Improve this answer. Jon Skeet Jon Skeet 1. That lately seems to be an argument, whether code testable or not. It's a rather flawed reasoning.
The argument should be 'good design', and usually good design is testable. But not the other way around: "I can't test it therefor it must be bad design. M Platvoet: I would say that given a choice between two otherwise equally valid designs, the testable one is superior.
Being testable certainly doesn't equate to being well designed, but I've rarely come across untestable good designs, and I think they're sufficiently rare that I have no problem in making testability a general purpose contributing indicator towards good design.
M Platvoet - Testability affects both maintainability and reliability, and I would consider those major factors in the quality of design. They're not the only factors, surely, but IMHO the cost of any given code is a combination of machine cycles, developer cycles, and user cycles. Testability hits two of those three. M Platvoet - Testability also tends to affect reusability, since a decoupled class is generally easier to reuse.
M Platvoet - I don't agree with your first comment here. I think if something can't be tested, then it IS bad design; because if I can't test it, I can't know that it works. Would you buy a car if the salesperson told you "The design of this model prevents it from being tested, so I don't know if it actually runs"? William McDowell 59 10 10 bronze badges. Jessica Brown Jessica Brown 7, 6 6 gold badges 42 42 silver badges 80 80 bronze badges.
I like your answer, I think it focuses on the right tradeoffs to consider around statics rather than some of the red herrings like concurrency and scope. Even though the singleton itself might be thread-safe e. Also, statics are not against the OOP paradigm. A lot of OOP fanatics will tell you that the class is an object, and the static method is a method of the class object, rather than it's instances.
This phenomenon is less present in Java. Other languages, such as Python allow you to use classes as variables and you can access static methods as methods of that object. The last line of the third paragraph should read, all your non-static variables , if I'm not mistaken. Object Lifetime , is one very important point that jessica mentioned.
Show 4 more comments. Evil is a subjective term. These are the two main issues I have with them. Preet Sangha Preet Sangha Add a comment. Not if I make my test only dependent on the object state. Which is easier, the less global state I have. Dependency injection has nothing to do with global state or global visibility- even the container itself is not global. Compared to "normal" code, the only extra thing that a container-managed object is visible to is to the container itself.
In fact, DI is very commonly used to avoid the Singleton Pattern. There are 2 main problems with static variables: Thread Safety - static resources are by definition not thread-safe Code Implicity - You do not know when a static variables is instantiated and whether or not it will be instantiated before another static variable.
I don't get the Thread Safety point, i think that nothing is thread safe unless you make it so. This does not seem to be related to static things at all, please correct me if i'm missing something. Zmaster - While it is true that thread-safety is not an issue exclusive to static variables, because by their definition they are to be called from and by different contexts, they are more prune to them — sternr.
But it is true that thread-safety needs often to be taken into account with static resources. You should consider clarifying the sentence. There are valid thread safe uses of static resources, for example. The Logger instance is or is not thread-safe independently of where you assign the pointer to it.
Keeping state in statics is probably not a good idea, but there is no reason it should not be thread-safe. If you would like more details, please read on… Why Not Use Statics?
Executing Tests Statics cause a real problem when running suites of unit tests together for example, with your Continuous Integration server.
Worse, failure might be based on the order in which the tests were run. Subtle Bugs If you work in high availability environment, or anywhere that threads might be started and stopped, the same concern mentioned above with unit test suites can apply when your code is running on production as well. Summary I hope this helps explain a few basic reasons why statics are problematic up.
One instance per JVM. Can be accessed by using class name No object require. Contains a single value applicable to all instances. They doesn't modify state of Object. Disadvantages: Static members are always part of memory whether they are in use or not.
You can not control creation and destruction of static variable. Usefully they have been created at program loading and destroyed when program unload or when JVM shuts down. You can make statics thread safe using synchronize but you need some extra efforts.
If one thread change value of a static variable that can possibly break functionality of other threads. You cannot override static methods. Serialization doesn't work well with them. This is done before the main method is called, and hence before the launch method is called.
The platform is not initialized yet at this point. The non-static member, on the other side, is initialized when class mvce is instantiated. The class mvce is instantiated internally by the launch method, after the toolkit has been properly initialized. Yes, they are very odd. I think the main reason for this is that because there are no instances, you can't have polymorphism, but that is not really the only reason for inheritance. Polymorphism is great, but sometimes you just want to borrow most of the functionality of the base class and add a few things of your own.
Because of this, sometimes you'll see static classes switched to use singleton patterns, just so that it can leverage the some functions from base set of classes. In my opinion this is a hacky attempt to close that gap, and it gets confusing and introduces a lot of unnatural complexity. The other option is aggregation, where the child class methods just pass calls through to the parent class methods, but this is requires a lot of code to stich it all together and isn't really a perfect solution either.
These days, static classes are usually just used as a replacement for global methods, i. So yes, static classes are weird. Ideally, it would be nice if they could be broken into their own concept that provided the flexibility and lightweight ease-of-use that you get from methods that don't need to be bound to an instance which we have now with static classes , and also group those methods into containers which we also have now , but also provide the ability to define a base entity from which it will inherit methods this is the part that is missing now.
Also, it would be great it was a seperate concept from classes, for exactly the reasons you raise, it just gets confusing because people naturally expect classes to be instances with properties and methods that can be created and destroyed. I think that the reason why the static block version is slower than the static method version could be due to the different JIT optimization that they get See this interesting article for more interesting information : Java Secret: Are static blocks interpreted?
Why are static variables considered evil? Asked 6 Months ago Answers: 5 Viewed 26 times. PS: please do correct me if my assumptions about statics are wrong.
They clutter up the global namespace and are slower to look up than local variables.
0コメント