Java 如何创建实用程序类?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25223553/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 23:54:29  来源:igfitidea点击:

How can I create an utility class?

javautilityutility-method

提问by user2693979

I want to create a class with utility methods, for example

例如,我想用实用方法创建一个类

public class Util {

   public static void f (int i) {...}

   public static int g (int i, int j) {...}

}

Which is the best method to create an utility class?

哪个是创建实用程序类的最佳方法?

Should I use a private constructor?

我应该使用私有构造函数吗?

Should I make the utility class for abstract class?

我应该为抽象类制作实用程序类吗?

Should I do nothing?

我应该什么都不做吗?

采纳答案by initramfs

For a completely stateless utility class in Java, I suggest the class be declared publicand final, and have a private constructor to prevent instantiation. The finalkeyword prevents sub-classing and can improve efficiency at runtime.

对于 Java 中完全无状态的实用程序类,我建议将该类声明为publicand final,并使用私有构造函数来防止实例化。该final关键字可以防止子类化并可以提高运行时的效率。

The class should contain all staticmethods and should not be declared abstract(as that would imply the class is not concrete and has to be implemented in some way).

该类应该包含所有static方法并且不应该被声明abstract(因为这意味着该类不是具体的,必须以某种方式实现)。

The class should be given a name that corresponds to its set of provided utilities (or "Util" if the class is to provide a wide range of uncategorized utilities).

应该为该类指定一个与其提供的实用程序集相对应的名称(如果该类要提供大量未分类的实用程序,则应命名为“Util”)。

The class should not contain a nested class unless the nested class is to be a utility class as well (though this practice is potentially complex and hurts readability).

该类不应包含嵌套类,除非嵌套类也将是一个实用程序类(尽管这种做法可能很复杂并且会损害可读性)。

Methods in the class should have appropriate names.

类中的方法应该有适当的名称。

Methods only used by the class itself should be private.

仅由类本身使用的方法应该是私有的。

The class should not have any non-final/non-static class fields.

该类不应具有任何非最终/非静态类字段。

The class can also be statically imported by other classes to improve code readability (this depends on the complexity of the project however).

该类也可以由其他类静态导入以提高代码可读性(但这取决于项目的复杂性)。

Example:

例子:

public final class ExampleUtilities {
    // Example Utility method
    public static int foo(int i, int j) {
        int val;

        //Do stuff

        return val;
    }

    // Example Utility method overloaded
    public static float foo(float i, float j) {
        float val;

        //Do stuff

        return val;
    }

    // Example Utility method calling private method
    public static long bar(int p) {
        return hid(p) * hid(p);
    }

    // Example private method
    private static long hid(int i) {
        return i * 2 + 1;
    }
}

Perhaps most importantly of all, the documentation for each method should be precise and descriptive. Chances are methods from this class will be used very often and its good to have high quality documentation to complement the code.

也许最重要的是,每种方法的文档都应该是精确和描述性的。很有可能这个类的方法会被经常使用,并且有高质量的文档来补充代码是很好的。

回答by dasblinkenlight

Making a class abstractsends a message to the readers of your code that you want users of your abstractclass to subclass it. However, this is not what you want then to do: a utility class should not be subclassed.

创建一个类abstract向代码的读者发送一条消息,即您希望您的abstract类的用户对其进行子类化。但是,这不是您想要做的:实用程序类不应被子类化。

Therefore, adding a private constructor is a better choice here. You should also make the class finalto disallow subclassing of your utility class.

因此,在这里添加私有构造函数是更好的选择。您还应该使该类final禁止对您的实用程序类进行子类化。

回答by duffy356

I would make the class finaland every method would be static.

我会上课final,每种方法都是static.

So the class cannot be extended and the methods can be called by Classname.methodName. If you add members, be sure that they work thread safe;)

所以类不能被扩展,方法可以被调用Classname.methodName。如果您添加成员,请确保它们工作线程安全;)

回答by michaldo

According to Joshua Bloch (Effective Java), you should use private constructor which always throws exception. That will finally discourage user to create instance of util class.

根据 Joshua Bloch (Effective Java),你应该使用总是抛出异常的私有构造函数。这将最终阻止用户创建 util 类的实例。

Marking class abstract is not recommended because is abstractsuggests reader that class is designed for inheritance.

不推荐标记类抽象,因为抽象暗示读者类是为继承而设计的。