Why are static variables considered evil?

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

    Summarising few basic Advantages & Disadvantages of using Static methods in Java:

    Advantages:

    1. Globally accessible i.e. not tied with any particular object instance.
    2. One instance per JVM.
    3. Can be accessed by using class name (No object require).
    4. Contains a single value applicable to all instances.
    5. Load up on JVM startup and dies when JVM shuts down.
    6. They doesn't modify state of Object.

    Disadvantages:

    1. Static members are always part of memory whether they are in use or not.
    2. You can not control creation and destruction of static variable. Usefully they have been created at program loading and destroyed when program unload (or when JVM shuts down).
    3. You can make statics thread safe using synchronize but you need some extra efforts.
    4. If one thread change value of a static variable that can possibly break functionality of other threads.
    5. You must know “static“ before using it.
    6. You cannot override static methods.
    7. Serialization doesn't work well with them.
    8. They don't participate in runtime polymorphism.
    9. There is a memory issue (to some extent but not much I guess) if a large number of static variables/methods are used. Because they will not be Garbage Collected until program ends.
    10. Static methods are hard to test too.

提交回复
热议问题