如果私有辅助方法可以是静态的,它们是否应该是静态的 [英] Should private helper methods be static if they can be static
问题描述
假设我有一个旨在实例化的类.我在类中有几个私有的帮助器"方法,它们不需要访问任何类成员,只对它们的参数进行操作,返回结果.
Let's say I have a class designed to be instantiated. I have several private "helper" methods inside the class that do not require access to any of the class members, and operate solely on their arguments, returning a result.
public class Example {
private Something member;
public double compute() {
double total = 0;
total += computeOne(member);
total += computeMore(member);
return total;
}
private double computeOne(Something arg) { ... }
private double computeMore(Something arg) {... }
}
是否有任何特别的理由将 computeOne
和 computeMore
指定为静态方法 - 或者有什么特别的理由不这样做?
Is there any particular reason to specify computeOne
and computeMore
as static methods - or any particular reason not to?
让它们保持非静态当然是最容易的,即使它们当然可以是静态的而不会造成任何问题.
It is certainly easiest to leave them as non-static, even though they could certainly be static without causing any problems.
推荐答案
我更喜欢这样的辅助方法 private static
;这将使读者清楚他们不会修改对象的状态.我的 IDE 还会以斜体显示对静态方法的调用,因此我无需查看签名就知道该方法是静态的.
I prefer such helper methods to be private static
; which will make it clear to the reader that they will not modify the state of the object. My IDE will also show calls to static methods in italics, so I will know the method is static without looking the signature.
这篇关于如果私有辅助方法可以是静态的,它们是否应该是静态的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!