为什么静态变量被视为邪恶? [英] Why are static variables considered evil?

查看:105
本文介绍了为什么静态变量被视为邪恶?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一名新的企业界Java程序员。最近我使用 Groovy 和Java开发了一个应用程序。我编写的所有代码都使用了相当多的静态代码。高级技术部门要求我减少使用的静力学数量。我用Google搜索了同样的东西,我发现很多程序员都反对使用静态变量。

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 number of statics. I was asked by the senior technical lot to cut down on the number of statics used. I've googled about the same, and I find that many programmers are fairly against using static variables.

我发现静态变量使用起来更方便。而且我认为它们也很有效(如果我错了请纠正我),因为如果我必须对一个类中的函数进行10,000次调用,我很乐意将该方法设置为静态并使用简单的 Class.methodCall()而不是用10,000个类的实例来混乱内存,对吗?

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?

此外静态减少了inter - 对代码其他部分的依赖性。他们可以充当完美的国家持有者。除此之外,我发现静态广泛应用于某些语言,如 Smalltalk Scala 。那么为什么程序员(特别是Java世界)对静态的压迫很普遍?

Moreover statics reduce the inter-dependencies on the other parts of the code. They can act as perfect state holders. Adding to this I find that statics are widely implemented in some languages like Smalltalk and Scala. So why is this oppression for statics prevalent among programmers (especially in the world of Java)?

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

PS: please do correct me if my assumptions about statics are wrong.

推荐答案

静态变量代表全局状态。这很难推理并且很难测试:如果我创建一个对象的新实例,我可以在测试中推断它的新状态。如果我使用的是使用静态变量的代码,它可能处于任何状态 - 任何东西都可以修改它。

Static variables represent global state. That's hard to reason about and hard to test: if I create a new instance of an object, I can reason about its new state within tests. If I use code which is using static variables, it could be in any state - and anything could be modifying it.

我可以继续使用很长一段时间,但是要考虑的更大的概念是,事物的范围越紧,理由就越容易。我们擅长思考小事情,但如果没有模块化,就很难推断百万线路系统的状态。顺便说一句,这适用于所有类型的东西 - 而不仅仅是静态变量。

I could go on for quite a while, but the bigger concept to think about is that the tighter the scope of something, the easier it is to reason about. We're good at thinking about small things, but it's hard to reason about the state of a million line system if there's no modularity. This applies to all sorts of things, by the way - not just static variables.

这篇关于为什么静态变量被视为邪恶?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆