Why are static variables considered evil?

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

    The issue of 'Statics being evil' is more of an issue about global state. The appropriate time for a variable to be static, is if it does not ever have more than one state; IE tools that should be accessible by the entire framework and always return the same results for the same method calls are never 'evil' as statics. As to your comment:

    I find static variables more convenient to use. And I presume that they are efficient too

    Statics are the ideal and efficient choice for variables/classes that do not ever change.

    The problem with global state is the inherent inconsistency that it can create. Documentation about unit tests often address this issue, since any time there is a global state that can be accessed by more than multiple unrelated objects, your unit tests will be incomplete, and not 'unit' grained. As mentioned in this article about global state and singletons, if object A and B are unrelated (as in one is not expressly given reference to another), then A should not be able to affect the state of B.

    There are some exceptions to the ban global state in good code, such as the clock. Time is global, and--in some sense--it changes the state of objects without having a coded relationship.

提交回复
热议问题