如果它们的类没有成员变量,所有方法都应该是静态的吗 [英] 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屋!