Why are static variables considered evil?

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

    Since no one* has mentioned it: concurrency. Static variables can surprise you if you have multiple threads reading and writing to the static variable. This is common in web applications (e.g., ASP.NET) and it can cause some rather maddening bugs. For example, if you have a static variable that is updated by a page, and the page is requested by two people at "nearly the same time", one user may get the result expected by the other user, or worse.

    statics reduce the inter-dependencies on the other parts of the code. They can act as perfect state holders

    I hope you're prepared to use locks and deal with contention.

    *Actually, Preet Sangha mentioned it.

提交回复
热议问题