简体   繁体   English

Java中的静态方法-最佳做法?

[英]Static method in Java - Best Practice?

I'm wondering, that using static method, like in example below, is good or bad behavior. 我想知道,使用静态方法(如下面的示例)是好是坏。 Let me know, what you think :) 让我知道你的想法 :)

class SomeClass{

    static String appendString(String text){
        return text + "a";
    }
}

This is pure example, but I'm using this kind of method a lot. 这是纯粹的示例,但是我经常使用这种方法。 Always I'm passing all required params, never use any content in method class. 我总是传递所有必需的参数,从不使用方法类中的任何内容。

In general as far as the result of the static method call, does not have any side effects, there is no issues with this approach. 通常,就静态方法调用的结果而言,没有任何副作用,这种方法没有问题。

Although, there is one gotcha that you have to have in mind. 虽然,您必须牢记一个陷阱。 Unit testing of classes calling your static methods. 调用静态方法的类的单元测试。 If you use actual object you can use test double and simulate (mock) behavior, which is not possible when referencing static methods. 如果您使用实际对象,则可以使用双重测试和模拟(模拟)行为,这在引用静态方法时是不可能的。

I like to use static methods for functions that are re-used a lot in my projects. 我喜欢对在我的项目中经常使用的函数使用静态方法。

So, in my opinion, if this method is going to be used in a lot of different classes, then make it static. 因此,我认为,如果要在许多不同的类中使用此方法,请使其变为静态。

It depends on the content of your method. 这取决于您的方法的内容。 Based on your example, I would say using the static identifier for the appendString method is valid. 根据您的示例,我会说对appendString方法使用静态标识符是有效的。 In general any method that does not require instance members of objects to be constructed yet can be static. 通常,任何不需要构造对象的实例成员但仍然可以是静态的方法。 If you are just doing manipulation on some value/data passed in (eg, converting degrees to radians) than that's perfectly ok. 如果您只是对传入的某些值/数据进行操作(例如,将度数转换为弧度),那完全可以。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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