如何创建实用程序类? [英] How can I create an utility class?

查看:126
本文介绍了如何创建实用程序类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

应该我什么都不做?

推荐答案

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

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

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

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

该类应该被赋予一个与其提供的实用程序集相对应的名称(如果是类,则为Util)是提供各种未分类的实用程序。)

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).

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

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.

该类不应该有任何非final / non-static类字段。

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).

示例:

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 compliment the code.

这篇关于如何创建实用程序类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆