Java 为什么静态方法不被视为良好的面向对象实践?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4002201/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why aren't static methods considered good OO practice?
提问by Mike
I'm reading Programming Scala. At the beginning of chapter 4, the author comments that Java supports static methods, which are "not-so-pure OO concepts." Why is this so?
我正在阅读Scala 编程。在第 4 章的开头,作者评论说 Java 支持静态方法,这是“不那么纯粹的 OO 概念”。为什么会这样?
采纳答案by Eddie
One reason that static methods aren't very OO that hasn't been mentioned so far is that interfaces and abstract classes only define non-static methods. Static methods thus don't fit very well into inheritance.
到目前为止还没有提到静态方法不是很面向对象的一个原因是接口和抽象类只定义了非静态方法。因此静态方法不太适合继承。
Note also that static methods do not have access to "super
", which means that static methods cannot be overridden in any real sense. Actually, they can't be overridden at all, only hidden. Try this:
另请注意,静态方法无法访问“ super
”,这意味着不能在任何真正意义上覆盖静态方法。实际上,它们根本无法被覆盖,只能隐藏。尝试这个:
public class Test {
public static int returnValue() {
return 0;
}
public static void main(String[] arg) {
System.out.println(Test.returnValue());
System.out.println(Test2.returnValue());
Test x = new Test2();
System.out.println(x.returnValue());
}
}
public class Test2 extends Test {
public static int returnValue() {
return 1;
}
}
When you run this, you won't get what you expect. Test.returnValue()
gives what you expect. Test2.returnValue()
hidesthe method of the same name in the superclass (it does not override it), and it gives what you would expect.
当你运行它时,你不会得到你所期望的。 Test.returnValue()
给出你所期望的。 在超类中Test2.returnValue()
隐藏同名方法(它不会覆盖它),它提供了您所期望的。
One might naively expect "non-statically" calling a static method to use polymorphism. It doesn't. Whatever class the variable is declared as is the one used to look up the method. This is bad form because someone might expect the code to do something different from what it actually does.
人们可能天真地期望“非静态地”调用静态方法来使用多态。它没有。无论变量声明为哪个类,都是用于查找方法的类。这是一种糟糕的形式,因为有人可能希望代码做一些与实际不同的事情。
This doesn't mean, "Don't use static methods!" It does mean that you should reserve use of static methods for those instances where you really want the Class object to own the method, and not just as a lazy way of making a singleton.
这并不意味着“不要使用静态方法!” 这确实意味着您应该为那些真正希望 Class 对象拥有该方法的实例保留使用静态方法,而不仅仅是作为制作单例的懒惰方式。
回答by Luis Miguel Serrano
Static methods are not so pure OO concepts because they can be invoked without an object actually being associated with them. You use the class itself. You invoke them like this Classname.method(...);
静态方法不是那么纯粹的 OO 概念,因为它们可以在没有实际关联的对象的情况下被调用。您使用类本身。你像这样调用它们Classname.method(...);
回答by Koteswara sarma
Concept of OO is talks about controlling/accessing data from an object, but static methods need not to be called using an object and they belong to class rather than object.
OO 的概念是谈论控制/访问来自对象的数据,但不需要使用对象调用静态方法,它们属于类而不是对象。
--Cheers
- 干杯
回答by Gabe
Don't confuse "not-so-pure OO concepts" with "bad practice". Being "pure OO" is not some panacea that you should attempt to achieve. Just because static methods don't take an instance variable as a parameter does not mean that they are not useful. Some things just don't lend themselves to objects, and they should not be forced into that mold just for the sake of "purity".
不要将“不那么纯粹的 OO 概念”与“不良实践”混淆。成为“纯 OO”并不是您应该尝试实现的灵丹妙药。仅仅因为静态方法不将实例变量作为参数并不意味着它们没有用。有些东西就是不适合物体,不应该仅仅为了“纯洁”而强迫它们进入那种模式。
Some people think that things should be "pure", and thus anything "impure" is bad practice. In reality, bad practice is just doing things that are confusing, hard to maintain, difficult to use, etc. Creating static methods that take an instance is bad practicebecause any method that takes an instance should probably be an instance method. On the other hand, things like utility and factory functions generally don't take an instance, so they shouldbe static.
有些人认为事物应该是“纯”的,因此任何“不纯”的东西都是不好的做法。实际上,不好的做法就是做一些令人困惑、难以维护、难以使用等的事情。创建采用实例的静态方法是不好的做法,因为任何采用实例的方法都应该是实例方法。另一方面,实用程序和工厂函数之类的东西通常不采用实例,因此它们应该是静态的。
If you're wondering why they're not "pure OO", it's because they are not instance methods. A "pure" OO language would have everything being an object and all functions be instance methods. Of course, that's not terribly useful all the time. For example, consider the Math.atan2
method. It takes two numbers and doesn't require any state. What object could you even make it a method of? In a "pure" OO language, Math
might itself be an object (a singleton, probably), and atan2
would be an instance method, but since the function doesn't actually use any state in the Math
object, it is also not a "pure OO" concept.
如果您想知道为什么它们不是“纯 OO”,那是因为它们不是实例方法。“纯” OO 语言将所有东西都是对象,所有函数都是实例方法。当然,这并不是一直都非常有用。例如,考虑Math.atan2
方法。它需要两个数字并且不需要任何状态。什么对象你甚至可以使一个方法的?在“纯”面向对象语言中,Math
它本身可能是一个对象(可能是单例),并且atan2
是一个实例方法,但由于该函数实际上不使用Math
对象中的任何状态,因此它也不是“纯面向对象” “ 概念。
回答by J?rg W Mittag
Object-orientation is about three things:
面向对象是关于三件事:
- messaging,
- local retention and protection and hiding of state-process, and
- extreme late-binding of all things.
- 消息传递,
- 状态过程的本地保留和保护和隐藏,以及
- 一切事物的极端后期绑定。
Of those three, the most important one is messaging.
在这三个中,最重要的一个是消息传递。
Static methods violate at least messaging and late-binding.
静态方法至少违反了消息传递和后期绑定。
The idea of messagingmeans that in OO, computation is performed by networks of self-contained objects which send messages to each other. Sending a message is the onlyway of communication/computation.
消息传递的概念意味着在 OO 中,计算是由相互发送消息的自包含对象网络执行的。发送消息是唯一的通信/计算方式。
Static methods don't do that. They aren't associated with any object. They really aren't methods at all, according to the usual definition. They are really just procedures. There's pretty much no difference between a Java static method Foo.bar
and a BASIC subroutine FOO_BAR
.
静态方法不会这样做。它们不与任何对象相关联。他们真的没有方法可言,按照通常的定义。它们实际上只是程序。Java 静态方法Foo.bar
和 BASIC 子程序之间几乎没有区别FOO_BAR
。
As for late-binding: a more modern name for that is dynamic dispatch. Static methods violate that, too, in fact, it's even in their very name: staticmethods.
至于后期绑定:一个更现代的名称是动态调度。静态方法也违反了这一点,事实上,它甚至在它们的名字中:静态方法。
Static methods break some very nice properties of object-orientation. For example, object-oriented systems are automatically capability-safe with objects acting as capabilities. Static methods (or really anystatics, be that static state or static methods) break that property.
静态方法破坏了面向对象的一些非常好的特性。例如,面向对象的系统自动具有功能安全性,对象充当功能。静态方法(或任何静态方法,无论是静态还是静态方法)破坏了该属性。
You can also execute every object in parallel in its own process, since they only communicate via messaging, thus providing some trivial concurrency. (Like Actors, basically, which shouldn't be too surprising, since Carl Hewitt created the Actor Model based on Smalltalk-71, and Alan Kay created Smalltalk-71 partially based on PLANNER, which in turn was created by Carl Hewitt. The close relationship between actors and objects is far from coincidental, in fact, they are essentially one and the same.) Again, statics (both static methods, and especiallystatic state) break that nice property.
您还可以在其自己的进程中并行执行每个对象,因为它们仅通过消息传递进行通信,从而提供一些微不足道的并发性。(基本上就像Actors一样,这应该不会太令人惊讶,因为 Carl Hewitt 基于 Smalltalk-71 创建了 Actor Model,而 Alan Kay 部分基于 PLANNER 创建了 Smalltalk-71,而后者又由 Carl Hewitt 创建。关闭演员和对象之间的关系绝非巧合,事实上,它们本质上是一体的。)同样,静态(静态方法,尤其是静态状态)破坏了这个很好的属性。
回答by Ilia Anastassov
Static methods cause tight coupling, which is a violation of good Object Oriented Design. The tight coupling of the calling code and the code within the static method cannot be avoided through Dependency Inversion because static methods inherently don't support object-oriented design techniques such as Inheritance and Polymorphism.
静态方法会导致紧耦合,这违反了良好的面向对象设计。通过依赖倒置无法避免调用代码和静态方法中的代码的紧密耦合,因为静态方法本质上不支持面向对象的设计技术,例如继承和多态。
Besides static methods are difficult to test because of these tightly-coupled dependencies, which oftentimes lead to third-party infrastructure that the code depends upon - like a database, and it makes it very difficult to change the behavior without actually going in and changing the code.
此外,由于这些紧密耦合的依赖关系,静态方法很难测试,这通常会导致代码依赖的第三方基础设施——比如数据库,这使得在不实际进入和更改的情况下很难改变行为。代码。
回答by Gul Md Ershad
Static methods aren't considered good OO practice due to below reasons:
由于以下原因,静态方法不被视为良好的面向对象实践:
1) Prevents from Re-usability:
1) 防止重复使用:
Static methods can't be overriden. It can't be used to in interface.
静态方法不能被覆盖。它不能在界面中使用。
2) Object Lifetime is very long:
2)对象生命周期很长:
Static methods remain in the memory for a log time and its garbage collection takes long time. Developer's don't have control on destroying or creating of Static variables. Excessive usage of static variables can result in the memory overflow.
静态方法会在内存中保留一段日志时间,并且其垃圾收集需要很长时间。开发人员无法控制静态变量的销毁或创建。静态变量的过度使用会导致内存溢出。
3) Also, some other points:
3)另外,还有一些要点:
It doesn't respect the encapsulation because object does't remain in the complete control of its state. It doesn't follow concepts like Inversion of control, loose coupling, dependency injection, etc.
它不尊重封装,因为对象不会完全控制其状态。它不遵循控制反转、松耦合、依赖注入等概念。