简体   繁体   中英

Criteria for Java static methods?

Someone told me:

If you are using Eclipse and don't see any blue words (ie member variables) in your methods, then those methods should really be static methods, as long as the parameters (if there are any) are primitive types, or (in the case of object references) are immutable and/or thread-safe.

Is there any other criteria that a Java developer should consider when deciding whether an instance method should really be a static method instead?

简单地说,如果它是纯粹的“辅助/函数”,它不会修改对象的内部状态,那么它就是静态方法的良好候选者。

... unless you plan to subclass and override the method.

as long as the parameters (if there are any) are primitive types, or (in the case of object references) are immutable and/or thread-safe.

I don't see why that is relevant. Any thread-safety considerations are exactly the same whether you make the method static or not. A static method with only immutable parameters (that also does not mess with static fields of the class) is thread-safe. If the parameters are not immutable and the method changes them and this becomes un-thread-safe, then making this an instance method won't help at all.

If you don't need an instance of an object to call the method it should be static. That is: If you only work with the parameters and no members of an object. Usually those are collected in utility or helper classes that are never instantiated (secure by declaring a private default constructor).

ps: concerning "blue words": You should always use the this. to access member variables and not count on your IDE as the code becomes quite unreadable once you use a simple viewer/editor.

您计划以全局方式为所有实例使用的任何函数都可以是静态的

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM