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

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

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

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


当前回答

从我的观点来看,静态变量应该只读取数据或变量创建的约定。

For example we have a ui of some project, and we have a list of countries, languages, user roles, etc. And we have class to organize this data. we absolutely sure that app will not work without this lists. so the first that we do on app init is checking this list for updates and getting this list from api (if needed). So we agree that this data is "always" present in app. It is practically read only data so we don't need to take care of it's state - thinking about this case we really don't want to have a lot of instances of those data - this case looks a perfect candidate to be static.

其他回答

因为没有人*提到它:并发。如果有多个线程读取和写入静态变量,那么静态变量可能会让您感到惊讶。这在web应用程序(例如ASP.NET)中很常见,它会导致一些相当令人恼火的错误。例如,如果有一个静态变量由页面更新,并且页面由两个人“几乎同时”请求,一个用户可能会得到另一个用户所期望的结果,甚至更糟。

静态减少了对代码其他部分的相互依赖。他们可以作为完美的国家持有者

我希望您已经准备好使用锁和处理争用。

*事实上,Preet Sangha提到过。

在我看来,你是在问静态变量,但你也在你的例子中指出了静态方法。

静态变量并不是邪恶的——它们被采用为全局变量,就像大多数情况下与最终修饰符结合的常量一样,但正如它所说的,不要过度使用它们。

静态方法又名实用方法。使用它们通常不是一个坏的做法,但主要的问题是它们可能阻碍测试。

作为一个伟大的java项目的例子,使用了大量的静态和做它的正确方式,请看看Play!框架。在SO中也有关于它的讨论。

与静态导入相结合的静态变量/方法也被广泛应用于方便java中声明性编程的库中,如:make it easy或Hamcrest。如果没有大量的静态变量和方法,这是不可能的。

所以静态变量(和方法)很好,但要明智地使用它们!

静态变量本身并没有什么问题。只是Java语法有问题。每个Java类实际上定义了两个结构——一个封装静态变量的单例对象和一个实例。在同一个源代码块中定义这两种代码是非常糟糕的,会导致代码难以阅读。Scala做得很好。

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

从我的观点来看,静态变量应该只读取数据或变量创建的约定。

For example we have a ui of some project, and we have a list of countries, languages, user roles, etc. And we have class to organize this data. we absolutely sure that app will not work without this lists. so the first that we do on app init is checking this list for updates and getting this list from api (if needed). So we agree that this data is "always" present in app. It is practically read only data so we don't need to take care of it's state - thinking about this case we really don't want to have a lot of instances of those data - this case looks a perfect candidate to be static.