使用私有静态方法 [英] Using private static methods
问题描述
您对使用私人静态方法有什么看法?
我个人更喜欢使用方法到非静态,只要它不需要访问任何实例字段。
Personally, I prefer using a static private method to non-static as long as it does not require access to any instance fields.
但我听说这种做法违反OOP原则。
But I heard that this practice violates OOP principles.
编辑:我想从风格视角而不是表现。
I am wondering from style prospective of view, not performance.
推荐答案
A private static
方法本身并不违反OOP本身,但是当你有很多这些方法在一个类不需要(和不能*)访问实例字段,你不是以OO方式编程,因为对象意味着对该状态定义在一起的状态+操作。你为什么要把这些方法放在那个类上,如果他们不需要任何状态?
A private static
method by itself does not violate OOP per se, but when you have a lot of these methods on a class that don't need (and cannot*) access instance fields, you are not programming in an OO way, because "object" implies state + operations on that state defined together. Why are you putting these methods on that class, if they don't need any state?
(*)=原则上,由于Java中的类级别可见性,类上的静态方法具有该类的一个对象,例如:
(*) = In principle, due to the class level visibility in Java, a static method on a class has access to instance fields of an object of that class, for example:
class Test
{
int field = 123;
private static void accessInstance(Test test)
{
System.out.println(test.field);
}
}
您需要将引用传递给实例 this
pointer)当然,但是你基本上模仿实例方法。只是提到这是为了完整性。
You need to pass in the reference to an instance (this
pointer) yourself of course, but then you are essentially mimicking instance methods. Just mentioning this for completeness.
这篇关于使用私有静态方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!