Why are static variables considered evil?

前端 未结 30 2711
既然无缘
既然无缘 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:05

    a) Reason about programs.

    If you have a small- to midsize-program, where the static variable Global.foo is accessed, the call to it normally comes from nowhere - there is no path, and therefore no timeline, how the variable comes to the place, where it is used. 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.

    b) Do you really only need one?

    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.

提交回复
热议问题