如果它们的类没有成员变量,那么所有方法都应该是静态的 [英] Should all methods be static if their class has no member variables
问题描述
我刚和我合作过的人发生过争吵,这真的让我烦恼。如果你的类只有 calculateRisk
或/和 calculatePrice
等方法,那么该类是不可变的,没有成员变量,如果方法是静态的,那么每次都不必创建类的实例。我使用以下示例:
I've just had an argument with someone I work with and it's really bugging me. If you have a class which just has methods like calculateRisk
or/and calculatePrice
, the class is immutable and has no member variables, should the methods be static so as not to have to create an instance of the class each time. I use the following example:
public class CalcService {
public int calcPrice(Trade trade, Date date) {
...
}
public double calcRisk(Trade trace, Date date) {
...
}
}
这些方法应该 static
?
推荐答案
您描述的类只是一组仅对输入进行操作的函数。将这些函数作为类的静态方法是完全合理的。这样做会逻辑地对它们进行分组并消除可能的名称冲突该类实际上充当命名空间,仅此而已。
The class you describe is simply just a set of functions that operate on inputs only. It's perfectly reasonable to make such functions static methods of a class. Doing so groups them logically and eliminates possible name conflicts. The class in fact acts as a namespace and nothing more.
这篇关于如果它们的类没有成员变量,那么所有方法都应该是静态的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!