我是一名Java程序员,刚进入企业界。最近我用Groovy和Java开发了一个应用程序。在我编写的所有代码中,都使用了相当多的静态元素。高级技术人员要求我减少使用的静态数据的数量。我在谷歌上搜索过相同的内容,我发现许多程序员都相当反对使用静态变量。

我发现静态变量使用起来更方便。而且我假定它们也是有效的(如果我错了请纠正我),因为如果我必须在一个类中对一个函数进行10,000次调用,我将很高兴使方法静态,并在其上使用直接的class . methodcall(),而不是用10,000个类实例使内存混乱,对吗?

此外,静态减少了对代码其他部分的相互依赖。他们可以作为完美的国家持有者。除此之外,我还发现一些语言(如Smalltalk和Scala)广泛地实现了静态。那么为什么程序员普遍反对静态(尤其是在Java世界中)呢?

PS:如果我对静态数据的假设是错误的,请纠正我。


当前回答

Static fields are de facto GC roots (see the How Garbage Collection Works section earlier in this chapter), which means they are never garbage-collected! For convenience alone, static fields and collections are often used to hold caches or share state across threads. Mutable static fields need to be cleaned up explicitly. If the developer does not consider every possibility (a near certainty), the cleanup will not take place, resulting in a memory leak. This sort of careless programming means that static fields and collections have become the most common cause of memory leaks!

简而言之,永远不要使用可变静态字段——只使用常量。如果您认为需要可变静态字段,请再三考虑!总有更合适的方法。

其他回答

总结在Java中使用静态方法的几个基本优点和缺点:

优点:

全局可访问,即不与任何特定的对象实例绑定。 每个JVM一个实例。 可以通过类名访问(不需要对象)。 包含一个适用于所有实例的值。 在JVM启动时加载,并在JVM关闭时死亡。 它们不会修改Object的状态。

缺点:

Static members are always part of memory whether they are in use or not. 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). You can make statics thread safe using synchronize but you need some extra efforts. If one thread change value of a static variable that can possibly break functionality of other threads. You must know “static“ before using it. You cannot override static methods. Serialization doesn't work well with them. They don't participate in runtime polymorphism. 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. Static methods are hard to test too.

还有一个原因:脆弱性。

如果你有一个类,大多数人都希望能够随意创建和使用它。

您可以记录这种情况,或者防止这种情况发生(单例/工厂模式)——但这是额外的工作,因此需要额外的成本。 即使这样,在大公司中,也有可能有人在某些时候尝试使用您的类,而没有完全注意到所有好的评论或工厂。

如果你经常使用静态变量,它就会崩溃。虫子是昂贵的。

在0.0001%的性能改进和可能不了解的开发人员更改的健壮性之间,在很多情况下健壮性是不错的选择。

以上所有答案都说明了为什么静态方法很糟糕。它们是邪恶的原因是因为它给人一种错误的印象,即你在编写面向对象的代码,而事实上你并不是。 这简直是邪恶。

我认为过度使用全局变量和静态关键字也会导致应用程序中实例的某些点的内存泄漏

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.

也就是说,区分常规静态变量(通常被认为是不好的)和最终静态变量(AKA常量;还不错)。