Why are static variables considered evil?

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

    Seems to me that you're asking about static variables but you also point out static methods in your examples.

    Static variables are not evil - they have its adoption as global variables like constants in most cases combined with final modifier, but as it said don't overuse them.

    Static methods aka utility method. It isn't generally a bad practice to use them but major concern is that they might obstruct testing.

    As a example of great java project that use a lot of statics and do it right way please look at Play! framework. There is also discussion about it in SO.

    Static variables/methods combined with static import are also widely used in libraries that facilitate declarative programming in java like: make it easy or Hamcrest. It wouldn't be possible without a lot of static variables and methods.

    So static variables (and methods) are good but use them wisely!

提交回复
热议问题