Why are static variables considered evil?

前端 未结 30 2729
既然无缘
既然无缘 2020-11-21 05:04

I am a Java programmer who is new to the corporate world. Recently I\'ve developed an application using Groovy and Java. All through the code I wrote used quite a good numbe

30条回答
  •  别那么骄傲
    2020-11-21 06:07

    I have just summarized some of the points made in the answers. If you find anything wrong please feel free to correct it.

    Scaling: We have exactly one instance of a static variable per JVM. Suppose we are developing a library management system and we decided to put the name of book a static variable as there is only one per book. But if system grows and we are using multiple JVMs then we dont have a way to figure out which book we are dealing with?

    Thread-Safety: Both instance variable and static variable need to be controlled when used in multi threaded environment. But in case of an instance variable it does not need protection unless it is explicitly shared between threads but in case of a static variable it is always shared by all the threads in the process.

    Testing: Though testable design does not equal to good design but we will rarely observe a good design that is not testable. As static variables represent global state and it gets very difficult to test them.

    Reasoning about state: If I create a new instance of a class then we can reason about the state of this instance but if it is having static variables then it could be in any state. Why? Because it is possible that the static variable has been modified by some different instance as static variable is shared across instances.

    Serialization: Serialization also does not work well with them.

    Creation and destruction: Creation and destruction of static variables can not be controlled. Usually they are created and destroyed at program loading and unloading time. It means they are bad for memory management and also add up the initialization time at start up.

    But what if we really need them?

    But sometimes we may have a genuine need of them. If we really feel the need of many static variables that are shared across the application then one option is to make use of Singleton Design pattern which will have all these variables. Or we can create some object which will have these static variable and can be passed around.

    Also if the static variable is marked final it becomes a constant and value assigned to it once cannot be changed. It means it will save us from all the problems we face due to its mutability.

提交回复
热议问题