我是一名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.
“静态是邪恶的”这个问题更多的是关于全局状态的问题。一个变量保持静态的适当时间是当它从来没有超过一个状态时;IE工具应该可以被整个框架访问,并且总是为相同的方法调用返回相同的结果,这些都不是静态的“邪恶”。关于你的评论:
我发现静态变量使用起来更方便。我认为他们也很有效率
对于永远不会改变的变量/类,静态是理想和有效的选择。
The problem with global state is the inherent inconsistency that it can create. Documentation about unit tests often address this issue, since any time there is a global state that can be accessed by more than multiple unrelated objects, your unit tests will be incomplete, and not 'unit' grained. As mentioned in this article about global state and singletons, if object A and B are unrelated (as in one is not expressly given reference to another), then A should not be able to affect the state of B.
在良好的代码中,有一些禁用全局状态的例外,例如时钟。时间是全局的,在某种意义上,它改变了对象的状态,而不需要编码关系。