Why are static variables considered evil?

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

    if I had to make 10,000 calls to a function within a class, I would be glad to make the method static and use a straightforward class.methodCall() on it instead of cluttering the memory with 10,000 instances of the class, Right?

    You have to balance the need for encapsulating data into an object with a state, versus the need of simply computing the result of a function on some data.

    Moreover statics reduce the inter-dependencies on the other parts of the code.

    So does encapsulation. In large applications, statics tend to produce spaghetti code and don't easily allow refactoring or testing.

    The other answers also provide good reasons against excessive use of statics.

提交回复
热议问题