Why are static variables considered evil?

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

    Static variables are generally considered bad because they represent global state and are therefore much more difficult to reason about. In particular, they break the assumptions of object-oriented programming. In object-oriented programming, each object has its own state, represented by instance (non-static) variables. Static variables represent state across instances which can be much more difficult to unit test. This is mainly because it is more difficult to isolate changes to static variables to a single test.

    That being said, it is important to make a distinction between regular static variables (generally considered bad), and final static variables (AKA constants; not so bad).

提交回复
热议问题