Why are static variables considered evil?

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

    I find static variables more convenient to use. And I presume that they are efficient too (Please correct me if I am wrong) because 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?

    I see what you think, but a simple Singleton pattern will do the same without having to instantiate 10 000 objects.

    static methods can be used, but only for functions that are related to the object domain and do not need or use internal properties of the object.

    ex:

    public class WaterContainer {
        private int size;
        private int brand;
        ...etc
    
        public static int convertToGallon(int liters)...
    
        public static int convertToLiters(int gallon)...
    
    }
    

提交回复
热议问题